代码之家  ›  专栏  ›  技术社区  ›  Kristinn Örn Sigurðsson

使用jquery使用.submit()事件处理程序循环窗体字段

  •  0
  • Kristinn Örn Sigurðsson  · 技术社区  · 15 年前

    我对jquery的表单提交有点问题。我以前用它提交过很多表单,但我只是在想,我如何使用事件处理程序.submit()提交表单,它是不调用表单ID的元素。问题是我似乎无法用$(this)链接元素(可以使用.children(),但我只想通过输入字段使用.each())。

    以下是代码段:

    $('.editTimeLink').click(function () {
        var id = $(this).attr('rel');
        $.get('<?php echo $config["httpRoot"]; ?>/ajax.php?ajax=1&sec=time&a=edit&id=' + id, {}, function (data) {
            if (data.returnCode == 1) {
                $('#timeBox_' + id).html(data.data);
                $('#timeBox_' + id + ' form').bind('submit', function () {
                    //$(this).$(':input').each(function () {
                    //$(this).(':input').each(function () {
                    $(this).each(':input', function () {
                        alert("adsf");
                    });
    
                    return false;
                });
            } else if (data.returnCode == 0) {
                alert(data.data);
            }
        }, 'json');
    
        return false;
    });
    

    如您所见,我正试图为表单“this”中的每个输入元素提醒字符串“asdf”。

    你可以看到这两行在哪里被注释掉了我一直试图管理的内容。没有注释掉的行也不起作用。我知道如何解决这个问题,例如,将表单选择器的名称传递给lambda函数,但我只是在想是否有一种更“干净”的方法可以做到这一点?

    事先谢谢。 克里斯汀。

    2 回复  |  直到 9 年前
        1
  •  1
  •   Brett Gregson    9 年前

    为什么你不能用 children() 是吗?你还可以用 each() .

    $(this).children(':input').each(...);
    

    但是,这不起作用:

    $(this).each(':input', function () {
        alert("test");
    });
    

    因为 () 只接受一个参数,一个回调( doc here )。

    顺便说一下:使用JS调试器,例如, Firebug ,是一个很好的方法来找出为什么东西不起作用。

        2
  •  2
  •   StuperUser    12 年前

    .children()选择直接子级,因此如果表单中有表或其他标记,则需要使用.find()。

    $(this).find(':input').each(function(i){
        console.log($(this).val()); //$(this) now contains the current form field in the loop
    });