[英]jQuery element is not changing text color when clicked
我的代碼沒有將#ffffff
元素的文本顏色更改為 #ffffff 。 沒有記錄錯誤。
JS代碼
$(document).ready(() => {
$('.label').on("click", () => {
$(this).css("color", "#ffffff")
})
})
HTML 代碼
<div id="q1">
<img src="lizerds/l2.jpeg" class="img"/>
<div>
<div class="radioWrapper">
<label class="label">
<input type="radio" id="q1Snake" class="radio" name="q1radio">
Snake
</label>
</div>
<div class="radioWrapper">
<label class="label">
<input type="radio" id="q1Lizard" class="radio" name="q1radio">
Legless Lizard
</label>
</div>
</div>
</div>
您不能在匿名 function 中使用this
來引用本地實例。 將箭頭 function 更改為“函數”,您的代碼將按預期工作:
$(document).ready(() => { $('.label').on("click", function() { $(this).css("color", "red") }) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="q1"> <img src="lizerds/l2.jpeg" class="img"/> <div> <div class="radioWrapper"> <label class="label"> <input type="radio" id="q1Snake" class="radio" name="q1radio"> Snake </label> </div> <div class="radioWrapper"> <label class="label"> <input type="radio" id="q1Lizard" class="radio" name="q1radio"> Legless Lizard </label> </div> </div> </div>
你快到了。 使用currentTarget
捕獲當前元素。
注意:請避免內聯 CSS,而不是內聯使用 class。
$(document).ready((elm) => { $('.label').on("click", (elm) => { var $this = $(elm.currentTarget); $('.label').removeClass('yourClss'); // Remove previous added class before add class in current markup $this.addClass('yourClss') }) })
.yourClss { color: #ffffff }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="q1"> <img src="lizerds/l2.jpeg" class="img" /> <div> <div class="radioWrapper"> <label class="label"> <input type="radio" id="q1Snake" class="radio" name="q1radio"> Snake </label> </div> <div class="radioWrapper"> <label class="label"> <input type="radio" id="q1Lizard" class="radio" name="q1radio"> Legless Lizard </label> </div> </div> </div>
發生此問題是因為您嘗試使用箭頭 function 來實現this
上下文。
正如MDN 官方文檔所說:
你應該這樣做:
$(document).ready(() => {
$('.label').on("click", function() {
$(this).css("color", "#ffffff")
})
})
而不是這個
$(document).ready(() => {
$('.label').on("click", () => {
$(this).css("color", "#ffffff")
})
})
您必須在 function 中捕獲當前元素。 請使用此代碼
$(document).ready((elem) => {
$('.label').on("click", (elem) => {
var current = $(elem.currentTarget);
$(current).css("color","#ffffff");
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.