【问题标题】:JQuery click events do not hide svgJQuery点击事件不隐藏svg
【发布时间】:2015-03-19 00:37:01
【问题描述】:

我正在尝试获得一个可以隐藏/显示和svg 元素的工作导航栏。然而,JQuery 没有正确响应。我的代码如下:

HTML

<header id="header"><h1 class="title">Test</h1></header>
<nav id="nav">
    <p class="text" data-index="0">Test</p>
    <p class="text" data-index="1">Test</p>
    <p class="text" data-index="2">Test</p>
    <p class="text" data-index="3">Test</p>
    <p class="text" data-index="4">Test</p>
</nav>
<div id="main" class="center">
    <svg width="1000" height="200" id="timeline">
        <line x1="0" y1="200"
              x2="1000" y2="200"
              stroke="black"
              stroke-width="4"/>
    </svg>
</div>

JavaScript

$(".text").click(function(event) {
    var index = $(event.target).data("index");
    switch(index) {
        case "0":
            $("#timeline").hide("slow");
            break;
        case "1":
            $("#timeline").show("slow");
            break;
    }
});

这是一个展示完整示例的 JSFiddle:https://jsfiddle.net/James_Parsons/s0gze1qq/1/

【问题讨论】:

  • 你忘了在你的小提琴中添加 jQuery 库;)
  • 对此很抱歉:P

标签: jquery svg


【解决方案1】:

索引是数字,而不是字符串,因此您应该使用:

Updated Example - (作为旁注,你没有包括 jQuery)

$(".text").click(function(event) {
    var index = $(event.target).data("index");
    switch(index) {
        case 0:
            $("#timeline").hide("slow");
            break;
        case 1:
            $("#timeline").show("slow");
            break;
    }
});

【讨论】:

  • 虽然属性是html中的字符串,所以JS也会返回一个字符串。
  • 不一定。由于 JS 不像 Java 那样是静态类型的,因此 value 可以解释为数字、字符串或布尔值。但我不知道为什么当它也可以是一个字符串时它会停在一个数字上。我希望有人回答:)
【解决方案2】:

问题在于您执行开关盒的方式。

var index = $(event.target).data("index");

这会返回一个数字而不是字符串值,因此请像下面这样更改您的开关盒,它将起作用。

    switch(index) {
        case 0:
            $("#timeline").hide("slow");
            break;
        case 1:
            $("#timeline").show("slow");
            break;
    }

这是一个 Fiddle fork 更新了更改:)

【讨论】:

    【解决方案3】:
    1. 您没有在 fiddle 中包含 jquery.min.js
    2. 改变

    来自

    var index = $(event.target).data("index");
    

    var index = $(this).data("index");
    

    JS代码会这样,

    $(".text").click(function(event) {
        var index = $(this).data("index");
        switch(index) {
            case "0":
                $("#timeline").hide("slow");
                break;
            case "1":
                $("#timeline").show("slow");
                break;
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2014-06-09
      • 1970-01-01
      • 2016-11-01
      • 2017-02-28
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      相关资源
      最近更新 更多