gpt4 book ai didi

javascript - 将函数作为事件处理程序的回调传递时,在我的 javascript 项目中获取不正确的值

转载 作者:行者123 更新时间:2023-11-30 00:14:06 25 4
gpt4 key购买 nike

这里我刚刚提取了我有问题的代码部分,因为它是一个带有 clickInfo 方法的对象,我想在单击 html 中的 testDivbtn 时使用它

var product = {
jsondata:[
{title:"GearBox", price:80000},
{title:"Clutch", price:7000}
],
loadInfo:function (event) {
​ // This line is printing first product info from the jsondata array​ - just to test
console.log (this.jsondata[0].title + " " + this.jsondata[0].price);
}
}

这是附加到点击处理程序的简单 div

$ ("#testDivbtn").click(product.loadInfo); 

这是html

<div class="col-sm6"><button id="#testDivbtn" type="button" class="btn btn-default">Test Product</button></div>

它在控制台中显示错误 - 无法读取未定义的属性“0”我在我的应用程序的许多其他地方都有这个错误,如果有任何一个错误指出它会非常有帮助。

最佳答案

您需要使用 bind

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

引用:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

最初当您使用 this.jsondata[0].title 时, 在这里 this指的是<button>元素,没有属性 .jsondata

$(function() {
var product = {
jsondata: [{
title: "GearBox",
price: 80000
}, {
title: "Clutch",
price: 7000
}],
loadInfo: function(event) {
console.log(this.jsondata[0].title + " " + this.jsondata[0].price);
}
}
$("#testDivbtn").click(product.loadInfo.bind(product));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm6">
<button id="testDivbtn" type="button" class="btn btn-default">Test Product</button>
</div>

填充:

if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}

var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};

if (this.prototype) {
// Function.prototype don't have a prototype property
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();

return fBound;
};
}

关于javascript - 将函数作为事件处理程序的回调传递时,在我的 javascript 项目中获取不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35389383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com