javascript jQuery - 重复 ID 的选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6850471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Selector for duplicate ID's
提问by KingKongFrog
I have a page with duplicate ID's for a form element. The catch is I the elements show up separately based on a toggle. So both ID's never show up simultaneously.
我有一个包含重复 ID 的表单元素页面。问题是我根据切换单独显示元素。所以这两个 ID 永远不会同时出现。
However when I do form validation on that element, it always selects the element displayed last in the code (even if its hidden).
但是,当我对该元素进行表单验证时,它总是选择代码中最后显示的元素(即使它是隐藏的)。
Is there a selector to select the visible duplicate ID?
是否有选择器来选择可见的重复 ID?
I've tried the following but to no avail:
我尝试了以下但无济于事:
$('#my_element:visible').val();
回答by Dereleased
As the myriad of other questions about this premise will tell you, you cannot use the ID selector #
in this case; you have to use something like $('div[id=foo]')
to find it.
正如关于这个前提的无数其他问题会告诉你的那样,#
在这种情况下你不能使用 ID 选择器;你必须使用类似的东西$('div[id=foo]')
来找到它。
回答by RwwL
Duplicate IDs are invalid HTML and will nearly always cause issues with scripting. Avoid if at all possible.
重复的 ID 是无效的 HTML,几乎总是会导致脚本问题。尽可能避免。
回答by Delebrin
The reason this is occurring is because of Duplicate IDs. IDs must be unique for the HTML to be considered valid. Whenever you aren't working against valid HTML, your results are often erratic.
发生这种情况的原因是 ID 重复。要使 HTML 有效,ID 必须是唯一的。每当您不针对有效的 HTML 工作时,您的结果通常是不稳定的。
In this case, even though you are only showing one of the forms at a time, they're both still present in the mark up which is why the last one in the code is always the one that's getting run.
在这种情况下,即使您一次只显示一个表单,它们仍然存在于标记中,这就是为什么代码中的最后一个总是运行的原因。
Since you're using jQuery, I'd highly recommend using classes for this instead.
由于您使用的是 jQuery,我强烈建议您为此使用类。
回答by Senica Gonzalez
as Rwwl said, duplicate IDs are invalid. Assign classes instead of ids to them.
正如 Rwwl 所说,重复的 ID 是无效的。为它们分配类而不是 id。
Then you can do
然后你可以做
alert($('.my_element:visible').val());
回答by diEcho
try :hidden
尝试:隐藏
$("#my_element").find(":hidden").val();
Elements can be considered hidden for several reasons:
元素可以被认为是隐藏的,原因有几个:
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
NOTE:Elements with visibility: hidden
or opacity: 0
are considered to be visible,
注意:带有visibility: hidden
或 的元素opacity: 0
被认为是可见的,
回答by ShankarSangoli
Avoid duplicates ids on the page. It is not a valid HTML.
避免页面上的重复 ID。它不是有效的 HTML。
回答by ChristopheCVB
Do not use same id for multiple elements, classes are better!
不要对多个元素使用相同的 id,类更好!