![](/img/trans.png)
[英]check if an element has length zero in an array and do something with that element on javascript
[英]check if element has something
首先,我從JSON接收一行數據並在HTML上打印數據
<p id="checker">1+2</p>
以下我有一些復選框
<p style="display:none" id="1">cat</p>
<p style="display:none" id="2">dog</p>
<p style="display:none" id="3">fish</p>
如果if語句為true,我想出現一些p標簽
if ($("#checker").html() == "1") {
$("#1").css("display", "block");
}
elseif($("#checker").html() == "2") {
$("#2").css("display", "block");
}
但我意識到這不能滿足我的需要。 這項任務還有另一種解決方案嗎?
拆分字符串並根據值get元素和show迭代它們。
$('#checker') .html() // get html content .split('+') // split string by + .forEach(function(v) { // iterate over them $('#' + $.trim(v)).show() // get element by id and show })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <p id="checker">1+2</p> <p style="display:none" id="1">cat</p> <p style="display:none" id="2">dog</p> <p style="display:none" id="3">fish</p>
是的,您可以使用jQuery show()
函數,如下所示:
if($("#checker").html()=="1"){
$("#1").show();
}
elseif($("#checker").html()=="2"){
$("#2").show();
}
如果需要再次隱藏它們,可以使用hide()
函數相同的方式。
有事並不意味着==
。 您可以使用indexOf檢查字符串是否包含某些內容。
試試這個
if($("#checker").html().indexOf("1")!=-1){
$("#1").css("display","block");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.