有 5 个按钮,每个按钮将执行不同的操作。
第一个按钮会将段落变为绿色(在 HTML 文件中,Id="button1"
)。
第二个按钮会将段落变为蓝色(在 HTML 文件中,Id="button2"
)。
window.onload = pageLoad;
function pageLoad() {
this.onclick = makeChange;
}
function makeChange() {
var paragraph = document.getElementById("paragraph");
if (this.id = "button1") {
paragraph.style.color = "green";
} else {
// change the color
}
}
这不起作用,因为我无法获取按钮的 ID,我尝试使用以下方法对其进行调试:
paragraph.innerHTML = this.id;// I got "undefined"
我是否可以获取按下哪个按钮,并根据按下哪个按钮,以不同方式更改文本颜色?我只想使用 1 个 function(exclude pageLoad)
来执行此操作,我没有 5 个 variableS 和 5 个 onclick
行,也没有 jquery .
var paragraph = document.GetElementById("button1");
var paragraph = document.GetElementById("button2");
var paragraph = document.GetElementById("button3");
....
最佳答案
你可以尝试这样的事情。使用自定义 data-*
属性,将要更改段落的颜色保留在按钮内。然后使用 .getAttribute()
访问它。所以你的 JS 应该是这样的:
function makeChange() {
var paragraph = document.getElementById("paragraph");
var newColor = this.getAttrbiute('data-color');
paragraph.style.color = newColor;
}
你的按钮应该是这样的:
<button data-color="green">Green</button>
<button data-color="blue">Blue</button>
这样您就可以通过更改data-color
属性轻松更改目标颜色。
作为旁注,请确保您正在使用按钮监听点击事件,如下所示:
var buttons = document.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', makeChange);
}
关于javascript - 如何使用 this.onclick 检查按钮 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47318834/