2011-04-10 71 views
5

我有以下的HTML如何获取jQuery的自定义HTML属性的每个()循环

<input type="text" name="first" expression="firstExpression"/> 
<input type="text" name="last" expression="secondExpression"/> 
<input type="text" name="age" expression="thirdExpression"/> 

我有一个自定义表达属性。

我使用jQuery遍历所有输入元素,虽然我需要稍后再做一些事情,但我需要能够获取每个输入元素的表达式值,并将其与的输入元素。

我能够通过执行以下操作

var expressionValue = inputs.attr("expression"); 

抢表达式的值,但只抓住下面的表达式的值,我需要能够做同样的事情,如以下情形

function showValues() 
{ 
    var inputs = $(":input[expression]"); 
    inputs.each(function(index){ 
    var input = inputs[index]; 
    //need to be able to get 'expression' from input var here 
    }); 
} 

上面的代码是否正确抓住我需要的所有元素,但我无法弄清楚如何抓住表达式的值属性

回答

12

使用$.each这样的:

function showValues() 
{ 
    var inputs = $("input[expression]"); 
    console.log(inputs); //output input for debug 
    inputs.each(function(){ 
     console.log(this,$(this).attr('expression'));//show expression (for debug) 
    }); 
} 

showValues(); 

拨弄:http://jsfiddle.net/maniator/LmW8P/

0

尝试

$(输入).attr( '表达'); //表达

1

尝试这种

$("input[expression]").each(function(){ 
    console.log($(this).attr('expression')); 
})
1

如果你所关心的是属性值,你可以选择a只需将function()传入.attr(),这将允许您迭代该集合。

Code example on jsfiddle.

0

此外,如果您在使用HTML5的自由,这将是最好的词“数据 - ”附加到自定义属性,因为这不会使该文件失效。

Custom Attributes: Yay or Nay

而且w3.org会谈的更多细节有关自定义更详细属性和还提到了一个数据集的属性能够很方便地访问所有这些元素都在脚本中,细节上W3.Org - Using Custom Attributes

希望这有助于!

相关问题