我可以使用 jQuery 独立地定位 CSS class 的实例吗?
Can I use jQuery to target instances of a CSS class independently?
我希望使用 jQuery 来更改 div 的背景颜色(我已经开始工作了!)但是单击一次会更改所有 div 的颜色,我想知道是否有任何方法可以在不影响其他元素的情况下更改已单击的特定元素的颜色?
$(document).ready(function() {
$(".bg").click(function() {
$(".bg").css("background-color", "red");
});
});
.bg {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bg">
<p id="demo" onclick="colorSwitch()">Click me to change my text color.</p>
</div>
<div class="bg">
<p id="demo" onclick="colorSwitch()">Click me to change my text color.</p>
</div>
<div class="bg">
<p id="demo" onclick="colorSwitch()">Click me to change my text color.</p>
</div>
<p>A function is triggered when the div element is clicked. The function sets the background-color of the div element to red.</p>
这里还有 JSFiddle:https://jsfiddle.net/davywest1000/jd82hq5t/2/
提前致谢!
您只需使用 $(this)
关键字来引用被点击的元素。
注意: 删除内联事件 onclick="colorSwitch()"
因为你已经在你的 JS 代码中附加了事件并且如果你想调用函数 colorSwitch
你可以在事件中调用它。
$(document).ready(function() {
$(".bg").click(function() {
$(this).css("background-color", "red");
});
});
.bg {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bg">
<p id="demo">Click me to change my text color.</p>
</div>
<div class="bg">
<p id="demo">Click me to change my text color.</p>
</div>
<div class="bg">
<p id="demo">Click me to change my text color.</p>
</div>
我希望使用 jQuery 来更改 div 的背景颜色(我已经开始工作了!)但是单击一次会更改所有 div 的颜色,我想知道是否有任何方法可以在不影响其他元素的情况下更改已单击的特定元素的颜色?
$(document).ready(function() {
$(".bg").click(function() {
$(".bg").css("background-color", "red");
});
});
.bg {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bg">
<p id="demo" onclick="colorSwitch()">Click me to change my text color.</p>
</div>
<div class="bg">
<p id="demo" onclick="colorSwitch()">Click me to change my text color.</p>
</div>
<div class="bg">
<p id="demo" onclick="colorSwitch()">Click me to change my text color.</p>
</div>
<p>A function is triggered when the div element is clicked. The function sets the background-color of the div element to red.</p>
这里还有 JSFiddle:https://jsfiddle.net/davywest1000/jd82hq5t/2/
提前致谢!
您只需使用 $(this)
关键字来引用被点击的元素。
注意: 删除内联事件 onclick="colorSwitch()"
因为你已经在你的 JS 代码中附加了事件并且如果你想调用函数 colorSwitch
你可以在事件中调用它。
$(document).ready(function() {
$(".bg").click(function() {
$(this).css("background-color", "red");
});
});
.bg {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bg">
<p id="demo">Click me to change my text color.</p>
</div>
<div class="bg">
<p id="demo">Click me to change my text color.</p>
</div>
<div class="bg">
<p id="demo">Click me to change my text color.</p>
</div>