提问人:adam 提问时间:9/30/2020 最后编辑:Mr. Polywhirladam 更新时间:9/30/2020 访问量:762
添加带有jQuery对象的自输入参数的onClick?
Add onClick with self input parameter of a jQuery object?
问:
HTML 中所需的输出:
<input onclick="someFunction(this)"/>
尝试:
var input = $("<input/>");
input.attr("onclick", "someFunction(this)");
$("#body").append(input)
结果:
<input onclick="[object Object]"/>
我试过使用:
input.click({param: "this"}, someFunction);
我还尝试用“输入”替换“this”。没有运气。
jQuery不是必需的,但是我需要动态完成。以上只是一个示例,实际对象具有更多属性。
答:
1赞
m1k1o
9/30/2020
#1
使用箭头函数,将被继承。this
input.on('click', () => someFunction(this))
评论
0赞
Mr. Polywhirl
9/30/2020
请注意,lambda 不会重新定义,因此您很好,但如果您使用 ,则会遇到范围问题。this
input.on('click', function() { someFunction(this) })
0赞
m1k1o
9/30/2020
Ofc,是的。这就是箭头功能的荣耀。
0赞
Anton
9/30/2020
在您的示例中不会是输入,也许您想要:?this
input.on('click', () => someFunction(input))
2赞
Anton
9/30/2020
#2
一切都在开箱即用......
下面是一个示例。只需点击input
var input = $("<input/>");
input.attr("onclick", "someFunction(this)");
$("#body").append(input);
function someFunction(obj) {
$('#result').css('color', 'red');
console.log(obj);
}
$('#result').text(input[0].outerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="body">
<div>This is your code:</div>
<div id="result"></div>
</body>
你也可以使用纯jQuery。这就是你需要的。$(this)
var input = $("<input id=\"xxx\"/>");
input.click(function() {
const theInput = $(this);
console.log(theInput[0]);
});
$("#body").append(input);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="body"></body>
1赞
Mr. Polywhirl
9/30/2020
#3
您可以在内存中创建侦听器,而不是将处理程序添加为属性。此版本允许您在函数调用之前将事件目标包装在 jQuery 对象中。
const someFunction = ($element) => {
console.log($element.prop('class'));
}
const $input = $('<input>', { class: 'foo' })
.on('click', (e) => someFunction($(e.target)))
.appendTo('body');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
但是,如果您确实需要将其添加为属性,则可以执行以下操作。
const someFunction = (element) => {
console.log($(element).prop('class'));
}
const $input = $('<input>', { class: 'foo' })
.attr('onclick', 'someFunction(this)')
.appendTo('body');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
评论
input.on('click', e => someFunction(e.target))