javascript 将 onclick 事件添加到超链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18308477/
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-10-27 11:25:38  来源:igfitidea点击:

Add onclick event to hyperlink

javascriptjquerydomjavascript-events

提问by Prakash

I have a string containing my html content in code behind link like this

我在链接后面的代码中有一个包含我的 html 内容的字符串,如下所示

<p><a href=\"http://www.google.com\">rrr</a></p>"

1.I need to add a onclick event to this link.

1.我需要给这个链接添加一个onclick事件。

2.Need to get the href value.

2.需要获取href值。

I dont have a id or class for the link so cant access it directly using Javascript. I am a newbie to Jquery. Kinda stuck in here. How can I achieve this ?

我没有链接的 id 或类,因此无法使用 Javascript 直接访问它。我是 Jquery 的新手。有点卡在这里。我怎样才能做到这一点?

I tried using the Javascript onclick solutions by preventing default functionality, but MY HTML CONTENT IS GENERATED AT RUNTIME. So whatever I write in document.ready doesnt seem to work at all.

我尝试通过阻止默认功能来使用 Javascript onclick 解决方案,但我的 HTML 内容是在运行时生成的。所以我在 document.ready 中写的任何内容似乎都不起作用。

采纳答案by Amith

Jquery with working jsbin - http://jsbin.com/azOSayA/1/edit

使用 jsbin 的 Jquery - http://jsbin.com/azOsayA/1/edit

$("a").click(function(e){
 var a_href = $(this).attr('href');
  e.preventDefault();
 });

回答by S. S. Rawat

Try this

试试这个

$('p a').click(function(){
    alert($(this).prop('href'));
});

FIDDLE

小提琴

回答by Eswara Reddy

Try this

试试这个

$("p a").click(function(e){
   e.preventDefault();
   var link = $(this).attr('href');
});

回答by Rohan Kumar

Try this,

试试这个,

$("p a").on('click',function(e){
   e.preventDefault();
   var link = $(this).attr('href');
   alert(link);
});

回答by Harry

Use

利用

 $("p a").click(
      function(e) {
           e.preventDefault();
           $(this).attr("href"); //do something with this
      }
 );

This will add a onclick listener to every link within the page which is a child of a paragraph.

这将为页面中的每个链接添加一个 onclick 侦听器,该链接是段落的子级。

If the link is really important, you should probably give it an id, so that it can be identified uniquely.

如果链接真的很重要,您可能应该给它一个 id,以便它可以被唯一标识。

回答by Harry

http://jsfiddle.net/Nyrsu/

http://jsfiddle.net/Nyrsu/

$(document).ready(function(){
   $("p").find("a").click(function(e){
    e.preventDefault();
    var href= $(this).prop("href");
  });
});