【发布时间】:2020-11-24 10:57:54
【问题描述】:
我想使用 javascript 函数来定义一个下拉类型元素,我将在页面创建过程中多次使用该元素。我的定义代码是这样的:
function getSingleColorDropdown(use_id, initial_text) {
let list_id = "dropdownList_" + use_id;
let text_id = "dropdownText_" + use_id;
let menu_id = "dropdownMenu_" + use_id;
html = "<div class='dropdown dropdown_inline'>\
<button id='" + list_id + "' data-toggle='dropdown' \
class='btn btn-secondary dropdown-toggle dropdown_text_wrapper' \
type='button' aria-haspopup='true' aria-expanded='false'>\
\
<span id='" + text_id + "' class='dropdown_text'>" + initial_text + "</span>\
\
</button>\
\
<div id='" + menu_id + "' class='dropdown-menu' \
aria-labelledby='" + list_id + "'>\
\
<button class='dropdown-item' type='button' value='red' \
onclick='storeSingleColorDropdown(" + text_id + ", this.value)'>\
red\
</button>\
\
<button class='dropdown-item' type='button' value='yellow' \
onclick='storeSingleColorDropdown(" + text_id + ", this.value)'>\
yellow\
</button>\
\
</div>\
\
</div>"
return html
}
function storeSingleColorDropdown(use_id, result) {
console.log(use_id)
console.log(use_id.id)
console.log(result)
document.getElementById(use_id).innerHTML = result;
}
它工作得很好,除非我将text_id 传递给onclick,而不是传递id(应该是"dropdownText_" + use_id),而是传递整行<span id='" + text_id + "' class='dropdown_text'>" + initial_text + "</span>。我不明白为什么会这样。我尝试了不同的传递text_id 的方法,但这是“有效”的唯一方法,因为它传递了一些东西而不是破坏。
我怎样才能让它在onclick 中适当地通过text_id?
【问题讨论】:
-
问题很简单,在 JavaScript 中,元素的 id 可以用来获取整个元素。所以 JavaScript 虽然你将整个元素作为参数传递给函数。
-
哦,这很有趣。那我怎么告诉它只传递 id 呢?
-
使用反引号标出 id 例如
`${text_id}` -
嗯,当我尝试
onclick='selectDropdown(`jQuery{text_id}`, this.value)'时,它实际上是通过jQuery{text_id}而不是评估它。如果我在引号之外尝试它(例如:onclick='selectDropdown(" + `jQuery{text_id}` + ", this.value)',它会中断。 -
你必须在反引号后面加上美元符号例如
onclick = 'selectDropdown(`${text_id}` )'
标签: javascript html parameters onclick