我正在制作一个用户脚本来添加两个 <a>
元素到一个页面并修改其他三个。从这三个中,我需要删除 href
和其他一些data-*
不需要的属性。然后,我想添加一个 title
并定义onclick
(调用函数)。之后,我需要添加两个 <a>
元素。
但是,应该调用的函数onclick
被跳过并且控制台抛出 sendFeedback is not defined
当点击两个新的<a>
时s。调用脚本内的函数不会引发该错误。另外,虽然我有一个 el.onclick = "sendFeedback(arg)"
,检查元素后没有 onclick。不过,新的有,因为它们是在脚本内创建的。
以下是脚本中不正确的部分:
const classes = ["success", "danger", "warning"];
const feedback_types = ["tp-", "fp-", "naa-"];
const descriptions = ["description 1", "description 2", "description 3"];
function sendFeedback(verdict) {
// Below is for testing purposes, the function has another content
console.info("Reached end of function; verdict is " + verdict);
};
for (var i = 0; i < 3; i++) {
console.log("Start of for loop with i = " + i); // (Just for testing, too)
var el = document.getElementsByClassName("feedback-button on-post text-" + classes[i]); // The two first classes are common, and there are three more classes: text-success, text-danger and text-warning
$(el).removeAttr("href data-method data-remote data-post-id");
$(el).attr("title", descriptions[i]);
// $(el).attr("onclick", "sendFeedback(feedback_types[i])"); // onclick is not defined when inspecting
el.onclick = "sendFeedback(feedback_types[i])"; // onclick is not defined when inspecting, too!
if (i == 0) {
$(el).before('<a title="some title here" class="feedback-button on-post text-success" onclick="sendFeedback(\'tpu-\')">✓😮</a>'); // add the first anchor element
} else if (i == 1) {
$(el).after('<a title="some title here" class="feedback-button on-post text-danger" onclick="sendFeedback(\'fpu-\')">✗😮</a>'); // add the second anchor element
}
}
// Add "cursor: pointer" to all feedback buttons
$(".feedback-button").css("cursor", "pointer");
如上所述,而 onclick
被定义了,三老<a>
还没有onclick
而在新的两个中,点击时出现错误'sendFeedback' is not defined
.
添加sendFeedback(feedback_types[1])
然而,在脚本的末尾,控制台输出:
Start of for loop with i = 0
Start of for loop with i = 1
Start of for loop with i = 2
Reached end of function; verdict is fp-
如何制作onclick
在 <a>
中定义并避免{function} is not defined
?
最佳答案
而不是
el.onclick = "sendFeedback(feedback_types[i])";
我会推荐 jQuery 方式(因为您已经在使用 jQuery)
$(el).click(function () {
sendFeedback(feedback_types[i])
})
这应该可以解决您的问题。
关于javascript - 尽管在脚本中定义了,但为什么在检查时会跳过函数并且未定义 onclick?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57449007/