使用jquery更改/替换Href参数

时间:2015-11-18 19:40:50

标签: jquery url parameters href

根据是否已选中复选框,我有一个要替换的网址参数:

<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替换为

即使没有勾选复选框,也总会返回p_add_institution?id = 55&amp; p_acknowledge = Y。

此外,当我将鼠标悬停在链接上时,我也希望显示正确的网址。

http://jsfiddle.net/u89usjnj/5

任何帮助都会受到赞赏,如果有人能解释为什么参数没有切换到N

由于

2 个答案:

答案 0 :(得分:1)

// 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

供参考:

  

经验法则是: .prop()方法应该用于布尔属性/属性以及html中不存在的属性   (例如window.location)。所有其他属性(你可以看到的属性)   html)可以并且应该继续使用.attr()进行操作   方法。   (http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/

答案 1 :(得分:0)

回答问题:

$("#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();
    }
});