问题描述
我在使用jQuery时遇到了一些麻烦。
I am having some trouble with jQuery.
我正在创建一个简单的CMS,并且在界面中我有一个页面列表,在每个列表项中都是一个编辑链接。我让jQuery用该编辑ID监听点击。然后它将查看父LI以查看它具有的id,以便用户可以将更改保存到数据库中的右侧pageId。
I am making a simple CMS and in the interface I have a list of pages, in each list item is an edit link. I made jQuery listen for clicks with that edit id. It will then look at the parent LI to see what id it has so the user can save the changes to the right pageId in the database.
我的列表
<ul id="sortable" class="ui-sortable">
<li class="sortable" id="listItem_1">
<a href="#" id="edit">edit</a>
<span id="title">List item 1</span>
</li>
<li class="sortable" id="listItem_2">
<a href="#" id="edit">edit</a>
<span id="title">List item 2</span>
</li>
etc..
</ul>
和javascript
And the javascript
<script type="text/javascript">
$(document).ready(function() {
$('a#edit').click(function(){
alert($(this).parent("li").attr("id"));
})
});
但只有第一个编辑链接作品。所有其他人都被忽略了。
您可以在此处查看问题,
But only the first edit link works. All the others just get ignored.You can see the problem working here, http://info.radio-onair.ath.cx/active/scms/admin/pages/test.html
提前致谢。
推荐答案
在HTML中, id
是指唯一标识符。换句话说,2个元素具有相同的 id
是违反标准的。这里的jQuery行为正确。
In HTML, id
refers to a unique identifier. In other words, it is against standards to have 2 elements with the same id
. jQuery here behaves correctly.
使用类
而不是 id
标识您的代码:
Use a class
instead of an id
to identify your tags as such:
HTML:
<ul id="sortable" class="ui-sortable">
<li class="sortable" id="listItem_1">
<a class="edit" href="#">edit</a>
<span id="title">List item 1</span>
</li>
<li class="sortable" id="listItem_2">
<a class="edit" href="#">edit</a>
<span id="title">List item 2</span>
</li>
etc..
</ul>
JavaScript:
$(document).ready(function() {
$('a.edit').click(function(){
alert($(this).parent("li").attr("id"));
})
});
或者,因为父标签似乎已经有了一个独特的类,你可以简单地用它来定位想要的标签。这会减少我称之为类噪声(将无用类定义为可以由其父级的唯一属性作为目标的目标元素)。
Alternatively, since the parent tag already seems to have a unique class, you could simply use it to target wanted tags. This would reduce what I call "class noise" (the defining of useless class to target element which could be targeted by their parent's unique attributes).
HTML:
<ul id="sortable" class="ui-sortable">
<li class="sortable" id="listItem_1">
<a href="#">edit</a>
<span id="title">List item 1</span>
</li>
<li class="sortable" id="listItem_2">
<a href="#">edit</a>
<span id="title">List item 2</span>
</li>
etc..
</ul>
JavaScript:
$(document).ready(function() {
$("li.sortable a:contains('edit')").click(function(){
alert($(this).parent("li").attr("id"));
})
});
这篇关于jQuery单击功能仅适用于第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!