在Javascript中,multiple onclick();Collect Date和Single函数



function t1() {
var show1 = document.getElementById("p1").innerHTML;
window.alert(show1)
}
function t2() {
var show2 = document.getElementById("p2").innerHTML;
window.alert(show2)
}
function t3() {
var show3 = document.getElementById("p3").innerHTML;
window.alert(show3)
}
<div>
<p id="p1">I am Headign 1</p>
<p id="p2">I am Headign 2</p>
<p id="p3">I am Headign 3</p>
</div>


<button onclick="t1();">Bt 1</button>
<button onclick="t2();">Bt 2</button>
<button onclick="t3();">Bt 3</button>

在这个程序中,有3个函数用于运行类似的程序。如何只使用一个函数并获取所有信息,正如我在这个程序中提到的。

尝试此解决方案

<script type = "test/javascript">
function t(i) {
let show = document.getElementById("p" + i).innerHTML;
window.alert(show);
}
</script>

<button onclick="t(1);">Bt 1</button>
<button onclick="t(2);">Bt 2</button>
<button onclick="t(3);">Bt 3</button>

您可以使用事件委派来实现这一点,因此<p>元素不需要id,并且请不要编写内联JS它有很多缺点

/* the onclick event can be delegated so you can have only one 
* listener for the parent element */
document.querySelector("div").onclick = function(e) {
// alert the innerHTML only if the element is a `<p>`
e.target.nodeName === "P" && alert(e.target.innerHTML);
}
<div>
<p>I am Headign 1</p>
<p>I am Headign 2</p>
<p>I am Headign 3</p>
</div>

最新更新