Change/Replace Href 参数与 jquery

Change/Replace Href parameter with jquery

我有一个 URL 参数,我想根据是否选中复选框来替换它:

<input id="acknowledge" type="checkbox" checked="checked" name="acknowledge" tabindex="">I accept

<a href="p_add_institution?id=55&p_acknowledge=Y" class="stronglink" id="add-institution">Add another institution</a>

如果复选框未选中,我想将 p_acknowledge 参数替换为 p_acknowledge=N,如果选中,则 p_acknowledge=Y。

它总是 return p_add_institution?id=55&p_acknowledge=Y 即使未选中该复选框。

此外,当我将鼠标悬停在 link 上时,我也希望显示正确的 URL。

http://jsfiddle.net/u89usjnj/5

任何帮助将不胜感激,如果有人能解释为什么参数没有切换到 N

谢谢

// Input with id acknowledge on change event
$("input#acknowledge").change(function(){

    // Fetch checkbox is checked or not
    var status = this.checked;

    // Decide what to set in href Y or N based on status
    var yorn = (status?"Y":"N");

    // Update the link using .attr
    $("#add-institution").attr("href", "p_add_institution?id=55&p_acknowledge="+yorn);
})

Play Here

仅供参考:

Rule of thumb is: .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method. (http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/)

回答问题:

$("#acknowledge").on("change", function(){
    $("#add-institution").attr("href", "p_add_institution?id=55&p_acknowledge=" + $(this).prop("checked") ? "Y" : "N");
});

但是,您也可以创建两个链接并相应地切换它们的显示:

HTML:

<input id="acknowledge" type="checkbox" checked="checked" name="acknowledge" tabindex="">I accept

<a href="p_add_institution?id=55&p_acknowledge=Y" class="stronglink" id="add-institution_Yes">Add another institution</a>
<a href="p_add_institution?id=55&p_acknowledge=N" class="stronglink" id="add-institution_No" style="display:none;">Add another institution</a> //Hidden by default

JQuery:

$("#acknowledge").on("change", function(){
    if ($(this).prop("checked")){
        $("#addinstitution-Yes").show();
        $("#addinstitution-No").hide();
    }
    else{
        $("#addinstitution-Yes").hide();
        $("#addinstitution-No").show();
    }
});