看一下下面的 HTML 和 JS:
HTML:
<button onclick="alertFunction()">Choose Option Modal (Button 1)</button>
<button onclick="alertFunction2()">Veloce Modal (Button 2)</button>
JS:
function alertFunction() {
alert("Please choose relevant options before adding to cart.");
}
function alertFunction2() {
alert("item(s) added to your cart");
}
$(function() {
(function() {
window.alert = function(text) {
if (text.indexOf("Please choose relevant options before")) {
console.log('Choose an Option Modal Open (Button 1)');
} else if (text.indexOf("item(s) added to your cart")) {
console.log('Veloce Modal Open (Button 2)');
}
};
})();
});
在上面的脚本中,如果我单击按钮(1 或 2),则会触发警报。接下来,JS 获取警报文本,我们检查警报文本。如果文本包含某些单词,则运行一个函数,在本例中只是一个 console.log
。
我遇到的问题是,当我单击按钮 1 时,会显示按钮 2 的 console.log
。如果我单击按钮 2,也会发生同样的情况,显示按钮 1 的 console.log
。
我有什么问题以及如何解决这个问题?
Here is a JSFiddle并提供了该问题的工作示例。
最佳答案
indexOf()
返回找到子字符串的第一个索引。在您的情况下,当文本匹配时,将返回 0
,其计算结果为 false
。任何其他内容,包括 -1
(表示未找到),都会计算为 true
。
检查返回值:
if (text.indexOf("Please choose relevant options before") > -1) {
console.log('Choose an Option Modal Open (Button 1)');
} else if (text.indexOf("item(s) added to your cart") > -1) {
console.log('Veloce Modal Open (Button 2)');
}
关于javascript - 脚本运行错误的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26894505/