[英]Why is function skipped and onclick not defined when inspecting, although defined in the script?
我正在制作一个用户脚本,将两个<a>
元素添加到页面并修改其他三个。 从这三个中,我需要删除href
和一些其他data-*
不必要的属性。 然后,我想添加一个title
并定义onclick
(调用函数)。 之后,我需要添加两个<a>
元素。
但是,单击两个新的<a>
时, sendFeedback is not defined
应调用onclick
的函数,并且控制台抛出sendFeedback is not defined
。 在脚本内调用该函数不会引发该错误。 另外,虽然我有一个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
而在两个新的<a>
, 'sendFeedback' is not defined
单击时, 'sendFeedback' is not defined
错误'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-
如何在<a>
定义onclick
并避免{function} is not defined
?
代替
el.onclick = "sendFeedback(feedback_types[i])";
我建议使用jQuery方式(因为您已经在使用jQuery)
$(el).click(function () {
sendFeedback(feedback_types[i])
})
这应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.