Javascript Jquery href 点击 - 如何触发事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14327250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:23:52  来源:igfitidea点击:

Jquery href click - how can I fire up an event?

javascriptjqueryhtml

提问by user1965451

I have this anchor and on click I would like to popup something. This href is within a page that has other hrefs.

我有这个锚点,点击我想弹出一些东西。此 href 位于具有其他 href 的页面内。

<a class="sign_new" href="#sign_up">Sign up</a>

jQuery:

jQuery:

$(document).ready(function(){
   $('a[href = "sign_up"]').click(function(){
      alert('Sign new href executed.'); 
   }); 
});

The above code does not fire up.

上面的代码没有启动。

回答by Selvakumar Arumugam

It doesn't because the href value is not sign_up.It is #sign_up. Try like below, You need to add "#" to indicate the id of the href value.

不是因为 href 值不是sign_up.It 是#sign_up. 尝试如下,您需要添加“#”来指示href值的id。

$('a[href="#sign_up"]').click(function(){
  alert('Sign new href executed.'); 
}); 

DEMO:http://jsfiddle.net/pnGbP/

演示:http : //jsfiddle.net/pnGbP/

回答by theadam

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

如果您拥有 HTML 代码,那么为这个 href 分配一个 id 可能是明智的。然后你的代码看起来像这样:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

和 jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

如果您不拥有 HTML,则需要将 $('#sign_up') 更改为 $('a.sign_new')。如果您在锚点中有一个 href 并且不想处理它,您也可能会触发 event.stopPropagation() (AFAIR return false 也可能有效)。

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

回答by Marcus

Try:

尝试:

$(document).ready(function(){
   $('a .sign_new').click(function(){
      alert('Sign new href executed.'); 
   }); 
});

You've mixed up the classand hrefnames / selector type.

您混淆了classhref名称/选择器类型。

回答by orique

You are binding the clickevent to anchors with an hrefattribute with value sign_new.

您将click事件绑定到带有值的href属性的锚点sign_new

Either bind anchors with class sign_newor bind anchors with href value #sign_up. I would prefer the former.

要么用 classsign_new绑定锚点,要么用 href 值绑定锚点#sign_up。我更喜欢前者。