如何从 javascript 函数获取 event.target 的 ID?
how to get id of event.target from javascript function?
例如:
function helloworld(){
alert("helloworld");
}
function worldhello(){
alert("worldhello");
}
两个功能和三个按钮。
单击'A'按钮将执行helloworld()
功能。
单击'B'按钮将执行worldhello()
功能。
点击'C'按钮时,执行helloworld ()
函数,执行worldhello ()
函数
我想阻止 helloworld()
函数的警报在单击 'C' 按钮时被执行。
我尝试使用event.target.id
和$(event.target).attr("id")
在[=]中找到'C'按钮的id
13=] 函数,但它打印了 undefined
.
如何在helloworld ()
函数中找到'C'按钮的id
?
我不明白你在获取元素 ID 后要做什么,无论如何,有更通用的方法可以做到这一点。您可以将标志传递给您的函数,以决定是否显示警报。
试试这个:
<button onclick="hw(true)">A</button>
<button onclick="wh(true)">B</button>
<button onclick="hw(false); wh(true)">C</button>
<script>
let hw = shouldAlert => {
if (shouldAlert) {
alert("Hello World!");
}
};
let wh = shouldAlert => {
if (shouldAlert) {
alert("World Hello!");
}
};
</script>
希望对您有所帮助!
例如:
function helloworld(){
alert("helloworld");
}
function worldhello(){
alert("worldhello");
}
两个功能和三个按钮。
单击'A'按钮将执行helloworld()
功能。
单击'B'按钮将执行worldhello()
功能。
点击'C'按钮时,执行helloworld ()
函数,执行worldhello ()
函数
我想阻止 helloworld()
函数的警报在单击 'C' 按钮时被执行。
我尝试使用event.target.id
和$(event.target).attr("id")
在[=]中找到'C'按钮的id
13=] 函数,但它打印了 undefined
.
如何在helloworld ()
函数中找到'C'按钮的id
?
我不明白你在获取元素 ID 后要做什么,无论如何,有更通用的方法可以做到这一点。您可以将标志传递给您的函数,以决定是否显示警报。
试试这个:
<button onclick="hw(true)">A</button>
<button onclick="wh(true)">B</button>
<button onclick="hw(false); wh(true)">C</button>
<script>
let hw = shouldAlert => {
if (shouldAlert) {
alert("Hello World!");
}
};
let wh = shouldAlert => {
if (shouldAlert) {
alert("World Hello!");
}
};
</script>
希望对您有所帮助!