使用jQuery获取输入值

时间:2013-10-21 16:25:31

标签: jquery jquery-selectors

我正在尝试在单击“删除”按钮之后和使用jQuery删除行之前从输入框中获取值。现在我只想尝试第一个盒子,但我的选择尝试没有运气。

以下是检索具有.editing类的输入值的最新尝试。顺便说一句,这不是所有的代码。 removeIng函数就像它应该的那样触发,我只是没有回到我需要的东西。

$('.remove_ing').click(removeIng);

function removeIng(){ //removes the row
    alert($(this).parentsUntil('tr').find('.editing').val());
    $(this).parent().parent().remove();
}

这是HTML,我有几行像这样(动态添加)

<tr>
  <td><input type='text' name='ingredient' value='' class='editing' /></td>
  <td><input type="text" class='editing_amt' name="amount" size="8" value="100"/></td>
  <td><select name='meas' class='editing_meas'></select></td>
  <td><input type="button" name="remove_ing" class="remove_ing" value="Remove"/></td>

</tr>

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

使用.on()

由于元素是动态添加的,因此无法将事件直接绑定到它们。因此,您必须使用Event Delegation

$(document).on('click','.remove_ing',removeIng);

function removeIng(){ //removes the row
    alert($(this).parentsUntil('tr').find('.editing').val());
    $(this).parent().parent().remove();
}

语法

$( elements ).on( events, selector, data, handler );

使用.closest()

相反

$(this).parent().parent().remove();

使用

$(this).closest('tr').remove();

答案 1 :(得分:0)

如果你的html是静态的(它不是动态的)你应该给按钮一个id,最好是tr。如果情况并非如此,那么事件委托就是最佳选择。 @Tushar给了你关于事件授权的想法。

无论如何,这里有一些可能对你有帮助的片段。

var btn = $(".remove_ing");
btn.click( removeIng );
function removeIng(){
    // get the row
    var tr = $(this).parents("tr").first();
    //get the text boxes
    var txt = tr.find("input[type='text']");
    //loop through the texts
    txt.each(function(){
        alert( $(this).val() );
    });
}

在这两种情况下(动态或静态html),此函数将获取所有输入文本。 希望它有所帮助。

相关问题