新版本的jQuery无法使用脚本

Script not working with new versions of jQuery

本文关键字:脚本 jQuery 新版本      更新时间:2023-09-26

这个使用jQuery添加/删除表格的简单脚本在1.3.2版本下运行良好。然而,在相同的页面上,我也使用需要jQuery> 1.6的脚本。这个脚本不再工作了,因为如果我第二次点击添加,它会删除一行,而不是添加它。

可以在这里找到一个工作示例:http://jsbin.com/arete3/edit#source

$(function(){
        $("input[type='button'].AddRow").toggle(
            function(){
                $(this).closest('tr').clone(true).prependTo($(this).closest('table'));
                $(this).attr("value", "Delete row");
            },
            function(){ 
               $(this).closest('tr').remove();          
        });
    });

要明白我的意思,请将jQuery版本更改为1.6以上的版本

有人有什么建议吗?

这里有一个脚本,可以满足您的要求。
我不知道你为什么用.toggle,因为一次是添加,下一次是删除。这是毫无意义的。

查看这个JSBin

我想这就是你要找的。

$(function(){
// Add row on click (on click of the add button)
$("input[type='button'].AddRow").click(function(){
    // Add the row
    $(this).closest('tr').clone(true).prependTo($(this).closest('table'));
});
// Delete row on click (on click of the delete button)
$("input[type='button'].DelRow").click(function(){
    // Delete the row
    $(this).closest('tr').remove();
});
}); // End DOM

你可以这样修改脚本

$("input[type='button'].AddRow").click(
function() {
    var index = $(this).closest('tr').index();
    if (index > 0) {
        $(this).closest('tr').remove();
    } else {
        $(this).closest('tr').clone(true).prependTo($(this).closest('table'));
        $(this).val("Delete row");
    }
});

此处提琴http://jsfiddle.net/nicolapeluchetti/fGam7/

你不能这样设置元素的"value"。使用".val ()":

$(this).val("Delete row");

从jQuery 1.6开始,".attr()"方法严格地(好吧,在1.6.1之后,几乎严格地)处理实际的属性,而不是属性,如<input>元素上的"value"。对于设置属性,您可以使用"。prop()",或者,特别是在"value"属性的情况下,使用"。val()"。

在1.6.1中所做的改变是减轻了几个布尔属性/属性的严格性,如"checked"answers"selected"。根据我个人的经验,即使使用这些方法,特别是在处理单选按钮时,坚持使用"prop()"更安全。

"属性"answers"属性"之间的区别似乎很微妙,但它确实很重要,特别是在IE中。"属性"是存储在DOM节点内部映射中的东西,可以通过"setAttribute()"answers"getAttribute()"方法访问。DOM节点的"属性"就像任何其他JavaScript对象属性一样。所以,因为要获取/设置<input> DOM节点的值,你会引用"值"属性,你使用"。prop()"或"。val()"来操纵它与jQuery。其他重要的属性有"src", "href", "className", "id", "name", "type", "tagName"等)

您可能还想考虑将表行添加到最近的<tbody>元素而不是<table>