-2

例如,

$(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以前的参数,我该怎么做?

4

3 回答 3

2

首先,有一种更好的附加元素的方法,试试这样的:

    $(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);
于 2013-08-21T19:38:32.610 回答
2

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

假设您的容器定义如下:

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

你可以使用这样的东西:

$('#container').on('click', 'img', function () {
   removeItem($(this).parent().attr('id'));
});
于 2013-08-21T19:09:06.380 回答
1

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

$(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 理想情况下,您应该将事件处理程序绑定到图像,而不是直接将其放入属性中。

于 2013-08-21T19:00:33.727 回答