【问题标题】:How to toggle css visibility with Javascript如何使用 Javascript 切换 CSS 可见性
【发布时间】:2014-06-23 16:38:37
【问题描述】:

我正在尝试创建一个类似于此处的常见问题解答页面:https://www.harrys.com/help 我想创建点击问题会显示答案的效果。

我的代码可以在这里看到:http://jsfiddle.net/8UVAf/1/

谁能告诉我为什么我的 javascript 不工作?我意识到我结合了 jQuery 和 Javascript,但我在某处读到它应该可以正常编译。

HTML:

<div class="questions-answer-block">
    <p class="question">This is a Question?</p>
    <p id="answer" class="hideinit">Here is the Answer</p>
</div>
<div class="questions-answer-block">
    <p class="question">This is a Question?</p>
    <p id="answer" class="hideinit">Here is the Answerdadawdawdawdawdawdawdawdwadawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawdawd</p>
</div>

JS:

$(".question").click(function (argument) {
    if(document.getElementById("answer").className.match(/(?:^|\s)hideinit(?!\S)/)) {
        document.getElementByID("answer").className = "display";
    }
});

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

基本上你的 Javascript 可以缩短为:

$(".question").click(function(argument) {  
    $(this).parent().find(".answer").removeClass("hideinit").addClass("display");
});

为了完成这项工作,您唯一需要做的另一件事就是将question 设为一个类而不是一个ID。看起来像:

<p class="answer hideinit">the answer</p>

See the fiddle here


编辑:添加隐藏/显示

要让它按预期隐藏和显示,您需要更新代码以在隐藏和显示之前检查当前类。看起来像:

$(".question").click(function(argument) {  
    var el = $(this).parent().find(".answer");
    if (el.hasClass("display")) {
       el.removeClass("display").addClass("hideinit");
    } else {
        el.removeClass("hideinit").addClass("display");
    }
});

See the fiddle here

【讨论】:

  • 这行得通!但是,我如何编辑 jQuery 以便再次单击问题后答案会消失?我宁愿不使用切换功能,因为我也想直接控制其他 css 属性。
  • 只需添加一个 if "has class" 并执行一个删除类。 (正在路上的例子)
【解决方案2】:

嗯,一方面,在您的 JSFiddle 中您没有包含 jQuery 库。我已经调整了你的代码,我想这就是你想要的:

$(".question").click(function() {
    $(this).siblings().toggle();
});

这是updated JSFiddle

【讨论】:

    【解决方案3】:

    请注意您的 JSFiddle 中包含的内容,因为您链接的版本不包括 jQuery 库。您还应该清理您的多个 id 引用(因为这是无效的 HTML,并且会导致一些问题)。

    除了这些问题,您可以使用 jQuery 的 .next() 方法来帮助您解决这个特殊问题:

    $(".question").click(function (argument) {
        $(this).next(".hideinit").removeClass("hideinit").addClass("display");
    });
    

    JSFiddle

    【讨论】:

      【解决方案4】:
      $(".question").on('click',function() {
          $(this).next().toggle();
      });
      

      【讨论】:

        猜你喜欢
        • 2018-12-17
        • 1970-01-01
        • 2013-07-12
        • 1970-01-01
        • 1970-01-01
        • 2014-03-02
        • 1970-01-01
        • 1970-01-01
        • 2020-12-26
        相关资源
        最近更新 更多