如何使用jQueryappend插入HTML部分包含onclick函数,该函数有一个参数



例如,

$(this).append('<div class="printText" id="'+inputVal +'">' + inputVal +
    '<img  onclick="removeItem('+ inputVal + ')" src="img/cross.png"height="25px" width="25px" style="float: right"></div>')

我想removeItem函数有一个以前的参数inputVal,我该怎么做?

由于添加的内容似乎是动态的,因此最好在追加发生之前声明事件处理程序。

假设您的容器定义如下:

<div id="container"></div>

你可以使用这样的东西:

$('#container').on('click', 'img', function () {
   removeItem($(this).parent().attr('id'));
});

首先,有一种更好的方法来附加元素,请尝试以下操作:

    $(this).append($('<div />').attr({
        'id': inputVal,
        'class': 'printText'
    }));
    $('#' + inputVal).append($('<img />')...now use functions to add src, id and so on);

现在添加onClick处理程序:

   $('#imageId').onclick = removeItem(inputVal);

您缺少传入值周围的引号:

$(this).append(
    '<div class="printText" id="'+inputVal +'">' + inputVal +
    '<img onclick="removeItem('' + inputVal + '')" src="img/cross.png"height="25px" width="25px" style="float: right"></div>'
    //                         ^^               ^^
);

PS理想情况下,应该将事件处理程序绑定到图像,而不是直接将其放在属性中。

最新更新