在 javascript 或 JQuery 中查找控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9428015/
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
Find control in javascript or JQuery
提问by sharmila
I have a dynamic html table generated using javascript. the table contains diffrent controls like textbox,dropdown box which has custom attributes.How can I loop through all the controls present inside this table and find the control whose custom attribute matches to some value?
我有一个使用 javascript 生成的动态 html 表。该表包含不同的控件,如文本框、具有自定义属性的下拉框。如何遍历该表中存在的所有控件并找到其自定义属性与某个值匹配的控件?
回答by kapa
This will give you all the form elements inside your table (:input
selector):
这将为您提供表格中的所有表单元素(:input
选择器):
var $formElements = $('#tableid').find(':input');
You can filter with an attribute selector:
您可以使用属性选择器进行过滤:
//will select every form element having a data-custom attribute set to 5
var $formElements = $('#tableid').find(':input[data-custom="5"]');
Please see the jsFiddle Demo. For my examples I used HTML5 data- attributes, but the code will work with any attribute you need.
请参阅jsFiddle 演示。对于我的示例,我使用了HTML5 数据属性,但代码可以处理您需要的任何属性。
OR you can use the filter()
methodto write a function that filters your elements:
或者您可以使用该filter()
方法编写一个过滤元素的函数:
var $formElements = $('#tableid').find(':input').filter(function () {
return $(this).attr('data-custom') == '5';
});
回答by mgraph
Demo : http://jsfiddle.net/DSqZr/1/
演示:http: //jsfiddle.net/DSqZr/1/
function getControl(_value){
$("#panel :input").each(function(){
if($(this).attr("custom") == _value){
return $(this);
}
})?
}
var selectedCrl = getControl(1);
回答by Tx3
You can use Attribute Contains Selector.
您可以使用属性包含选择器。
Check the example it is probably very close to what you need which is finding input
& select
elements with certain attribute values
检查示例它可能与您需要的非常接近,即查找具有某些属性值的input
&select
元素
回答by elclanrs
Give them a class .control
and:
给他们上课,.control
然后:
$('.control[attribute=value]')
Check Selectors APIfor more on attribute selectors.
检查选择器 API以获取有关属性选择器的更多信息。