Add onclick event to hyperlink [closed]

廉价感情. 提交于 2019-12-12 02:53:47

问题


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

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

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

2.Need to get the href value.

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 ?

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.


回答1:


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

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



回答2:


Try this

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

FIDDLE




回答3:


Try this

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



回答4:


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.

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




回答5:


Try this,

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



回答6:


http://jsfiddle.net/Nyrsu/

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


来源:https://stackoverflow.com/questions/18308477/add-onclick-event-to-hyperlink

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!