简体   繁体   English

改变的HREF <a>不工作</a>

[英]Changing href of <a> Not working

I want to change the href of tag using jquery. 我想使用jquery更改标签的href。

This is the html code: 这是html代码:

<a href="exampleurl" id="a_theme"  onClick="return activate_theme();">Click</a>

This is the jquery code: 这是jQuery代码:

function activate_theme(){
  $("#a_theme")).attr("href", "new url");
}

It displays an error : 它显示一个错误:

activate_theme is not defined

You are doing it wrong, probably because activate_theme() is defined in a scope inaccessible from your onClick handler. 您做错了,可能是因为activate_theme()onClick处理程序无法访问的范围内定义。 You have also a syntax mistake (double ) in jQuery call). 你也有一个语法错误(双) jQuery中调用)。

Just replace your code with this: 只需用以下代码替换您的代码:

<a href="exampleurl" id="a_theme">Click</a>

and with JavaScript: 并使用JavaScript:

$(function(){
    $("#a_theme").attr("href", "new url");
});

which will be executed as soon as DOM is ready, and will replace href for specified link. DOM准备就绪后将立即执行,并将替换href为指定的链接。

See working demo here: http://jsfiddle.net/tadeck/mHtHc/ 在这里查看工作演示: http : //jsfiddle.net/tadeck/mHtHc/

1st way: 第一种方式:

$(function(){
$("#a_theme").click(
    function(){
        $("#a_theme").attr("href", "new url");
    }
);
});

<a href="#" id="a_theme">Click</a>

2nd way: 第二种方式:

function activate_theme(){
    $("#a_theme").attr("href", "new url");
}


<a href="#" id="a_theme" onClick="activate_theme()">Click</a>
try with this also:

$('#a_theme').click(function(){
 $(this).attr('href', 'new_url');
});

but if you have more then one id with the same name then : 但是,如果您有多个同名ID,则:

$('#a_theme').each(function(i, e){
    $(this).click(function(){
     //same url on all '#a_theme' on click
     $(this).attr('href', 'new_url');
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM