问题
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