可以从单击的类中获取id,但不能从单击的id中获取类

Can get id from clicked class, but not class from clicked id

本文关键字:获取 id 单击 但不能      更新时间:2023-09-26

这是我测试的jsfiddlehttp://jsfiddle.net/5hhRF/

有数字1 2 1 2……当你点击最后一个数字"2"时,它不会发出警报。

我是不是漏掉了那个案子的代码?

我再次在这里复制相同的代码。

<span class="open-option" id="option1" >1</span>
<span class="open-option" id="option2" >2</span>
<span id="open-option" class="option1" >1</span>
<span id="open-option" class="option2" >2</span>​
$(".open选项").click(function(){var myID=$(this).attr('id');警报(myID);});$("#open option").click(function(){var myClass=$(this).attr('class');alert(myClass);});​

click事件仅绑定到具有给定id的第一个元素。

页面中的ID必须是唯一的。

不能为多个元素分配相同的id。

http://htmlhelp.com/reference/html40/attrs.html

ID属性唯一标识文档中的元素。不在单个文档中,两个元素可以具有相同的ID值。

jQuery id selector返回一个数组,但只包含带有id的DOM中的第一个元素。因此,在您的代码中,click handler is being applied to 1st DOM elements only

您可以使用包含选择器

$("span[id*='open-option']").click(function(){                    
   var myClass=$(this).attr('class');
   alert(myClass);
});

小提琴:http://jsfiddle.net/5hhRF/4/

恐怕元素ID必须是唯一的,如这里所示。否则,您的代码根本无法工作。