3

我有一个名称相同但 ID 不同的表单。我能够序列化数组,但无法获取当前 ID。

<form action="test.php" id="loginform" name="loginform" method="post">
     <input name="title[]" id="title1" type="text" value="" tabindex="1" />
     <input name="title[]" id="title2" type="text" value="" tabindex="2" />
     <input  name="title[]" id="title3" type="text" value="" tabindex="3" />
     <input type="submit" name="submit" value="Submit" id="submit" tabindex="4" />
 </form>

$('#loginform').bind('submit', function() { 
    var elements = $(this).serializeArray();
    $.each(elements, function(i, element) {
        var temp = $('#' + element['name']);
       var name = this.name; alert(name);
 var id = $(this).attr("id");alert(id); 
        (temp.val() == '') ? temp.css({'background': '#FFC4C4', 'border': '1px solid #F00'}) : temp.removeClass('hightlight');
    });
    return false;
});

我得到了名字但没有 id。任何人都可以看看这个....

演示

4

2 回答 2

2

I think I understand your question, but I'm not 100% certain. If my understanding is correct, you are trying to iterate through your inputs and get the ID attribute of each.

If that's all you need to do, there is a much simpler way of achieving it.

$('#loginform').submit(function(ev) {
    $('input[type=text]', this).each(function(index, element) {
      alert($(element).attr('id'));
    });
    ev.preventDefault();
});

So, a quick breakdown:

  • Firstly, $('input[type=text]', this) gets all text inputs from the form we are submitting.
  • Then, we iterate through them using .each().
  • For each element, we use .attr() to get the ID, and pass it to alert() to display to the user.

Updated Demo

于 2011-09-21T16:56:53.373 回答
0

.serializeArray()将只返回每个对象的名称和值。因此,迭代集合不会为您带来价值。

.serializeArray()

将一组表单元素编码为名称和值的数组。

于 2011-01-27T11:23:27.840 回答