0

下面,我试图遍历输入元素中的每个属性。它不工作,我不知道为什么。这是对名为 input 的对象的错误使用吗?我该如何改变?

<script>
   $('form.trade').submit(function(e) {
      e.preventDefault();
      input=$(this).find(':input:first');
      value='';

      $.each(input.attributes, function(i, attrib){
        if (attrib.name!='type'){
            value +=attrib.name + ":" + attrib.value + ";";
        }
      });
      });
</script>
<form class="trade" id="24243">
<input type="hidden" available="4" pid="24243" cardname="something" yay="blah">
Available: <p class="available">4</p>
<input type="submit" value="add card">
</form>
<br/>
<form class="trade" id="24245">
<input type="hidden" available="7" pid="24243" cardname="somethik" yay="blakk">
Available: <p class="available">7</p>
<input type="submit" value="add card">
</form>
4

3 回答 3

1

It's "attributes" on the input array that doesn't make sense.

$.each(input.attributes

The result of $(this).find(':input') returns a jQuery selection (array) of items.

Are you trying to iterate through the inputs attributes? $.each(input[i].attributes is what you're looking to do, where i is an iterator through the input collection.

~ Here's what you want to do:

<script>
      $('form.trade').submit(function(e) {
           e.preventDefault();
           var $inputs=$(this).find(':input:first');
           var value='';
           $inputs.each(function(i,input){
             $.each(input.attributes, function(j,attrib){
                 if (attrib.name!=='type'){
                value +=attrib.name + ":" + attrib.value + ";";
                 }   
             });
           });
           console.log(value); // what do you want to do with value??
      });
</script>
于 2013-01-22T19:32:32.373 回答
0

我想我必须先通过输入。我不知道为什么,但它很容易解决它。

        value='';
        input.each(function(){
        $.each(this.attributes, function(i, attrib){
            if (attrib.name!='type'){
                value +=attrib.name + ":" + attrib.value + ";";
            }
        });
        });
于 2013-01-22T19:52:25.547 回答
0

你可以使用普通的 javasript:

var elem = document.getElementById('testElement');
for (var i = 0; i < elem.attributes.length; i++) {
    var att = elem.attributes[i];
    if (att.specified == true) {
    console.log(att.name + " " + att.value);
    }
}

如何遍历 HTML 元素中的所有属性?

于 2013-01-22T20:06:11.593 回答