[英]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.