我正在尝试通过具有类名称的元素循环,并在其中找到输入值:
document.querySelectorAll('.qty').forEach(element=>{
console.log($(this).find('input').val())
})
这返回undefined
但是,如果我将上述代码更改为:
document.querySelectorAll('.qty').forEach(element=>{
console.log($('.qty').find('input').val())
})
不是this
是否应该用数量来屈服类名。this
为什么不起作用?
,因为您使用的是不包含其this
绑定的箭头功能。使用普通的ES5功能:
document.querySelectorAll(".qty").forEach(function(element) {
console.log($(this).find("input").val());
});
要使您的代码更简洁,您可以使用jQuery的内置功能,并丢弃未使用的element
参数。
$(".qty").each(function() {
console.log($(this).find("input").val());
});
或忘记this
并使用该参数,该参数允许您使用箭头功能:
$(".qty").each((_, e) => console.log(e.find("input").val()));
$(this(forEach
内部代表全局窗口对象。如果您喜欢使用jQuery将其更改为$('.qty').each
,而不是使用querySelectorAll
$('.qty').each((i, v) => {
console.log($(v).find('input').val())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='qty'>
<input type="text" value="1"></div>
<div class='qty'>
<input type="text" value="1"></div>
<div class='qty'>
<input type="text" value="1"></div>
<div class='qty'>
<input type="text" value="1"></div>
javaScript中的这种行为有所不同。其值由调用函数(运行时绑定(确定。
有关进一步说明,请参阅此文档:
https://developer.mozilla.org/en-us/docs/web/javascript/reference/reference/operators/this