事件 returns [object MouseEvent] 而不是文本
Event returns [object MouseEvent] rather than the text
我有我的 p 标签,它应该在我触发鼠标悬停事件时更改文本,但不知何故我在 return 而不是文本中得到了 [object MouseEvent]。
HTML
<p id="album-name-1"
onmouseover="changeText('follow me around, greatest song of the album!')">
change the text
</p>
JS
var par = document.querySelector("#album-name-1");
par.addEventListener("mouseover", changeText);
function changeText(text) {
if (this.id === "album-name-1") {
par.innerHTML = text;
}
}
我想通过使用 "this" 关键字来做到这一点,但不知何故它没有像我期望的那样工作。有什么建议吗?
因为你在 addEventListener
添加了 mouseover
事件侦听器,回调的第一个参数是事件。
相反,您可以将 this
作为参数传递给 onmouseover
属性。
var par = document.querySelector("#album-name-1");
function changeText(elem, text) {
if (elem.id === "album-name-1") {
par.innerHTML = text;
}
}
<p id="album-name-1" onmouseover="changeText(this, 'follow me around, greatest song of the album!')">
change the text
</p>
不要使用事件属性。它们满满的,总有一天会咬你的
相反,如果您真的想在标记中包含该文本,请将其存储在 data-
属性中并从您通过 addEventListener
.[=15 附加的事件处理程序中检索它=]
var par = document.querySelector("#album-name-1");
par.addEventListener("mouseover", changeText);
function changeText(evt) { // first param is the Event object
if (this.id === "album-name-1") { // 'this' is the current target
// all the data- attributes of our element
// are stored in its .dataset property
par.innerHTML = this.dataset.text;
}
}
<p id="album-name-1" data-text="follow me around, greatest song of the album!">
change the text
</p>
我有我的 p 标签,它应该在我触发鼠标悬停事件时更改文本,但不知何故我在 return 而不是文本中得到了 [object MouseEvent]。
HTML
<p id="album-name-1"
onmouseover="changeText('follow me around, greatest song of the album!')">
change the text
</p>
JS
var par = document.querySelector("#album-name-1");
par.addEventListener("mouseover", changeText);
function changeText(text) {
if (this.id === "album-name-1") {
par.innerHTML = text;
}
}
我想通过使用 "this" 关键字来做到这一点,但不知何故它没有像我期望的那样工作。有什么建议吗?
因为你在 addEventListener
添加了 mouseover
事件侦听器,回调的第一个参数是事件。
相反,您可以将 this
作为参数传递给 onmouseover
属性。
var par = document.querySelector("#album-name-1");
function changeText(elem, text) {
if (elem.id === "album-name-1") {
par.innerHTML = text;
}
}
<p id="album-name-1" onmouseover="changeText(this, 'follow me around, greatest song of the album!')">
change the text
</p>
不要使用事件属性。它们满满的
相反,如果您真的想在标记中包含该文本,请将其存储在 data-
属性中并从您通过 addEventListener
.[=15 附加的事件处理程序中检索它=]
var par = document.querySelector("#album-name-1");
par.addEventListener("mouseover", changeText);
function changeText(evt) { // first param is the Event object
if (this.id === "album-name-1") { // 'this' is the current target
// all the data- attributes of our element
// are stored in its .dataset property
par.innerHTML = this.dataset.text;
}
}
<p id="album-name-1" data-text="follow me around, greatest song of the album!">
change the text
</p>