例如,
$(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
以前的参数,我该怎么做?
例如,
$(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
以前的参数,我该怎么做?
首先,有一种更好的附加元素的方法,试试这样的:
$(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);
由于您添加的内容似乎是动态的,因此最好在追加发生之前声明事件处理程序。
假设您的容器定义如下:
<div id="container"></div>
你可以使用这样的东西:
$('#container').on('click', 'img', function () {
removeItem($(this).parent().attr('id'));
});
您缺少传入的值周围的引号:
$(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 理想情况下,您应该将事件处理程序绑定到图像,而不是直接将其放入属性中。