我相同的功能分配到2个不同的div元素。我想功能,以确定哪个div元素称为由它的ID的功能。没有jQuery的。
我只是不知道如何与价值观在我假设是,如果语句比较充足。
<head>
<script>
var x = document.getElementById('one')
var y = document.getElementById('two')
function foo(){
if(????){
x.style.color='red'
}
else if(????){
y.style.color='red'
}
}
</script>
<style>
#one, #two{width:50px; height:50px; border: solid black 5px;}
</style>
</head>
<div id='one' onclick='foo()'>hello</div>
<div id='two' onclick='foo()'>world</div>
基本上有DIV“一个” || “二”呼叫函数foo()和具有负责ID的属性之一改变。
您可以通过DIV的ID为foo。
<div id='one' onclick='foo(this.id)'>hello</div>
<div id='two' onclick='foo(this.id)'>world</div>
然后你可以使用给定id的函数foo这样的:
function foo(id) {
document.getElementById(id).style.color = 'red';
}
function foo(id) {
document.getElementById(id).style.color = 'red';
}
#one, #two{width:50px; height:50px; border: solid black 5px;}
<div id='one' onclick='foo(this.id)'>hello</div>
<div id='two' onclick='foo(this.id)'>world</div>
传递event
对象,并打通currentTarget
元素:
function foo(e){
const currEl = e.currentTarget;
if (currEl.id === 'one') {
currEl.style.background = 'red';
}
if (currEl.id === 'two') {
currEl.style.background = 'green';
}
}
<div id='one' onclick='foo(event)'>hello</div>
<div id='two' onclick='foo(event)'>world</div>
如果我没有记错的内联JS的disencouraged。
你可以这样做:
更改HTML这样的:
<div class="mycatchid" id='one' >hello</div>
<div class="mycatchid" id='two' >world</div>
并使用此JS:
[...document.querySelectorAll('.mycatchid')].forEach(elem =>{
elem.addEventListener('click', function(){
if(this.id == 'one') { console.log(this.id)}
else console.log(this.id);
})
});
一些笔记,在ES6完成后,可以检查一个活生生的例子:https://jsfiddle.net/jrzh9wxL/