javascript 将 id 用于 if 条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19304343/
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
Using the id for if condition
提问by Neil Porven
What is the correct way of addressing the id of an element in an if statement condition?
在 if 语句条件中处理元素 id 的正确方法是什么?
if($('id').val() == Reset)
var Submit_Status = $("#Reset").val();
else
var Submit_Status = $("#Nb_var97").val();
Thanks, Neil P.
谢谢,尼尔 P。
回答by Mike H.
Since I can't see your HTML I'm going to post a simple example:
由于我看不到您的 HTML,我将发布一个简单的示例:
<div id="myID"></div>
if($("div").attr("id") == "myID")
{
//do stuff
}
回答by Hacknightly
if($('someSelector').attr('id') == 'Reset')
var Submit_Status = $("#Reset").val();
else
var Submit_Status = $("#Nb_var97").val();
回答by Tallboy
if ( $('div').attr('id') == 'Reset' ) {
// do something
}
回答by Jamie Dixon
If you're trying to check the value of the ID property then you can get it using the attr
method.
如果您尝试检查 ID 属性的值,则可以使用该attr
方法获取它。
For example, if you were looping through all of the elements with the class foo
and wanted to check for the id bar
you could do this in your loops:
例如,如果您使用类循环遍历所有元素foo
并想检查 id bar
,则可以在循环中执行此操作:
...
var id = item.attr("id");
if(id == 'bar')
{
}
Here's an example where all divs on the page are selected and each one has it's ID checked in turn:
这是一个示例,其中选择了页面上的所有 div,并依次检查每个 div 的 ID:
var divs = $('div');
divs.each(function(index, value) {
var id = $(value).attr('id');
if(id == 'foo')
{
// Do foo work
}
else if(id == 'bar')
{
// Do bar work
}
Working example: http://jsfiddle.net/gZHMD/1/
工作示例:http: //jsfiddle.net/gZHMD/1/
回答by The Alpha
Using a short form (ternary/conditional operator) instead of if
使用简短形式(三元/条件运算符)而不是if
// element could be any html element but inputs have val and div, spans and suchlike don't have val
var Submit_Status = $('element').attr('id') == 'Reset' ? $("#Reset").val() : $("#Nb_var97").val();
Also, if you have multiple elements, then you have to select specific one, an example here.
此外,如果您有多个元素,那么您必须选择特定的一个,例如这里。