Javascript 如何按值查找输入元素ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2772502/
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
How to find input element id by value?
提问by Abs
How do I get the id of an input element based on its value? The values will always be unique and there are only seven of them. I have tried this:
如何根据输入元素的值获取其 id?这些值将始终是唯一的,并且只有七个。我试过这个:
$('#wrapper').find("input[value='"+value+"']").each(function(){
return this.id;
});
But nothing is returned!
但是什么都没有返回!
回答by DannyLane
Try
尝试
$(this).idnope, this.id works, no need to create a jQuery object for the ID.
$(this).id不,this.id 有效,无需为 ID 创建 jQuery 对象。
or
或者
$(this).attr('id')
HTH
HTH
EDIT: This might work:
编辑:这可能有效:
$('#wrapper').find("input[value='"+value+"']").attr('id');
回答by nkrkv
You write return this.id;… Return where? You simply return value from anonymous functions and I don't see where you ever trying to use it. So the answer is:
你写return this.id;……返回哪里?您只需从匿名函数返回值,而我看不到您曾尝试使用它的地方。所以答案是:
var idYouAreSearchingFor = $('#wrapper').find("input[value='"+value+"']").attr('id');
回答by meo
your code is almost good:
你的代码几乎是好的:
$('#wrapper').find("input[value='"+value+"']").each(function(){
return $(this).attr("id")
});
check here http://jsfiddle.net/5xsZt/
在这里查看 http://jsfiddle.net/5xsZt/
edit: i have just tested it with this.idit works to. Your code is right. Your error is somewhere else: check it:
http://jsfiddle.net/5xsZt/3/
编辑:我刚刚测试了this.id它的工作原理。你的代码是对的。您的错误在其他地方:检查一下:http:
//jsfiddle.net/5xsZt/3/
回答by Tim Down
Here's a version that will definitely work in all mainstream browsers:
这是一个绝对适用于所有主流浏览器的版本:
function getInputWithValue(wrapper, value) {
var inputs = wrapper.getElementsByTagName("input");
var i = inputs.length;
while (i--) {
if (inputs[i].value === value) {
return inputs[i];
}
}
return null;
}
var wrapper = document.getElementById("wrapper");
var input = getInputWithValue(wrapper, "some value");
window.alert(input.id);

