the index value of attribute

馋奶兔 提交于 2019-12-12 11:24:37

问题


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

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