简体   繁体   English

我可以使用 jQuery 使 DIV 及其内容可见和不可见吗?

[英]Can I make a DIV and its contents visible and invisible with jQuery?

I have DIVs on my form.我的表格上有 DIV。 I would like to use javascript to make these visible or invisible depending on some operation.我想根据某些操作使用 javascript 使这些可见或不可见。 Currently I am doing this:目前我正在这样做:

$('#token2').html("<div style='padding: 2px 4px; -moz-border-radius:5px; -webkit-border-radius:5px; border-radius:5px; border: 1px solid Red;'><span style='color: Red; '>Incorrect</span></div>");

and setting the contents of the DIV each time.并且每次设置DIV的内容。 Is there a way I can set this in CSS and just change a visible property instead?有没有办法可以在 CSS 中设置它,而只是更改可见属性?

$(#token2).toggle() will toggle the visibility, show() and hide() do the specific operations. $(#token2).toggle() 将切换可见性, show() 和 hide() 执行特定操作。 Give it the style "display: hidden" to start it off invisible.给它样式“显示:隐藏”以使其不可见。

How about .hide() and .show() ? .hide( .hide().show()怎么样?


Not directly related to your question, but since you mentioned CSS, I'd really recommend just defining the styles outside of the HTML...embedded in the JS... something like this:与您的问题没有直接关系,但既然您提到了 CSS,我真的建议您只在 HTML 之外定义 styles ......就像这样:

#token2 > div {
    padding: 2px 4px;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    border: 1px solid red;
}

#token2 > span {
    color: red;
}

which simplifies the JavaScript down to这将 JavaScript 简化为

$('#token2').html('<div><span>Incorrect</span></div>');

although the .html() part is really irrelevant anyway, with the previously mentioned jQuery methods.尽管.html()部分确实无关紧要,但使用前面提到的 jQuery 方法。

use this用这个

.hidden {display:none}

<span id="incorrect-answer"  class="hidden">Incorrect</span>

and then use jQuery.addClass and.removeClass to make it visible/invisible然后使用 jQuery.addClass 和.removeClass 使其可见/不可见

eg例如

$("#incorrect-answer").addClass("hidden")
$("#incorrect-answer").removeClass("hidden")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM