问题
I am using the following code ... ...
for($i=0; $i<90; $i++){
?>
<a id='read[<?php print $i; ?>]' href="<?php print $textToshow; ?>"> Text Shown</a>
<?php } ?>
I want to know the id of the a href when a user clicks on it. Something like read[1] read[2] etc
回答1:
$('a').click(function( e ) {
alert(this.id);
// e.preventDefault(); // Uncomment this line if you don't want
}); // to follow the link's href.
This assigns a click
event to all <a>
elements that will alert its ID when clicked.
Uncomment the e.preventDefault() line to prevent the default behavior of the link (following its href
).
It would probably be best to add a class attribute to the links, and select using that:
$('a.someClass').click(function( e ) {
alert(this.id);
// e.preventDefault(); // Uncomment this line if you don't want
});
This selects <a>
elements with the class "someClass"
using the class selector.
回答2:
Here you go
$('a[id^=read]').click(function(){
alert(this.id);
return false;
});
I use the attribute-starts-with selector to target the links that have an id
that starts with read
来源:https://stackoverflow.com/questions/4221269/the-index-value-of-attribute