[英]trouble using $.data() to change state for click event
大家提前謝謝。 在下面的代碼中,我想從數據值=“ no”的#foo div開始,單擊時我應該能夠執行操作並將其值更改為“ yes”。 然后,當我再次單擊div時,我想將值更改回“ no”,並且每次單擊都應該發生相同的情況。 我的邏輯有什么問題,我嘗試使用attr()這樣的不同方式來執行此操作。 我做不完
<div id = "foo" data-clicked="no"> #FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO </div>
$(document).ready( function(){
//在這里,如果數據屬性為: data-clicked="no"
那么當我單擊foo時,div應該將值更改為yes並在控制台中警告“更改為yes”,
if($("#foo").data("clicked") === "no"){
$("#foo").on("click",function(){
$("#foo").data("clicked","yes");
alert("changed to yes")
console.log($("#foo").data("clicked"))
})
}
如果數據更改為是,為什么下面的代碼不等於true? 它不起作用
if($("#foo").data("clicked") === "yes"){
$("#foo").on("click",function(){
$("#foo").attr("data-clicked", "no");
$("#foo").data("clicked","no");
alert("off")
console.log($("#foo").data("clicked"))
console.log($("#foo").attr("data-clicked"))
})
}
});
我也在下面嘗試了,但沒有用...是我的邏輯嗎?
$("#foo").on("click", function(){
if($(this).attr("data-clicked") == "no"){
alert("turn on");
$(this).attr("data-clicked", "yes")
}
if($(this).attr("data-clicked") == "yes"){
alert("turn off")
$(this).attr("data-clicked", "no")
}
})
看來您只是基於原始值設置了on處理程序。 將邏輯放在函數中可以解決此問題(可以通過多種方式完成。請參見以下示例
示例1:使用else if
jQuery(document).ready(function() { // over here if the data atribute: data-clicked="no" then when I click on foo the div should change the value to yes and alert "changed to yes" in the console, which it does jQuery("#foo").on("click", function() { if ($(this).data("clicked") === "no") { jQuery(this).data("clicked", "yes"); alert("changed to yes"); console.log(jQuery(this).data("clicked")) } else if ($(this).data("clicked") === "yes") { jQuery(this).data("clicked", "no"); alert("off"); console.log(jQuery(this).data("clicked")); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="foo" data-clicked="no">#FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO</div>
示例2:使用switch語句
jQuery(document).ready(function() { // over here if the data atribute: data-clicked="no" then when I click on foo the div should change the value to yes and alert "changed to yes" in the console, which it does jQuery("#foo").on("click", function() { switch ($(this).data("clicked")) { case "no": jQuery(this).data("clicked", "yes"); alert("changed to yes"); console.log(jQuery(this).data("clicked")) break; case "yes": jQuery(this).data("clicked", "no"); alert("off"); console.log(jQuery(this).data("clicked")); break; } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="foo" data-clicked="no">#FOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO</div>
只需您可以這樣做。
<div clicked='no'> </div>
$('#foo').on('click', function(){
$('#foo').attr('clicked') == 'no' ? $('#foo').attr('clicked', 'yes') : $('#foo').attr('clicked', 'no');
}
請參考此方法: http : //api.jquery.com/attr/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.