javascript - div#d1 切换到 p#1 点击 - 如何?

标签 javascript jquery

我试图在单击名称时切换 div。

  • 我的页面中有多个这样的耦合,我希望它像 “当 <p id= "d2"> 被点击时 => <div id="d2"> 被切换”。

我试过那些函数:

$(document).ready(function(){
    $("p").click(function(){
        $("div#" + $(this).attr('id')).toggle();
    });
});

function rgt() {
    //document.body.innerHTML = "";
    var id = "d" + this.id;
    var situation = document.getElementById(id).style.display;

    if (situation == "none") {
        situation = "block";
    }
    else {
        situation = "none";
    }
}

 function showHide(theId) {
    if (document.getElementById("d" + theId).style.display == "none") {
        document.getElementById("d" + theId).style.display = "block";
    }
    else {
        document.getElementById("d" + theId).style.display = "none";
    }
}

我做不到!!!这是为什么?

浏览器说:“no 'display' property for null”...

我很乐意用简单的 jquery 解决它

最佳答案

确保您的 id 属性是唯一的

假设您的 id 属性是唯一的,they are required to be per the specification :

The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

您应该考虑将您的 id 属性重命名为 d{n} 并将您的段落分别重命名为 p{n} ,如下所示:

<button id='p1'>p1</button> <button id='p2'>p2</button> <button id='p3'>p3</button>
<div id='d1'><pre>d1</pre></div>
<div id='d2'><pre>d2</pre></div>
<div id='d3'><pre>d3</pre></div>

这将允许您使用以下函数来处理您的切换操作:

$(function(){
  // When an ID that starts with P is clicked
  $('[id^="p"]').click(function(){
      // Get the proper number for it
      var id = parseInt($(this).attr('id').replace(/\D/g,''));
      // Now that you have the ID, use it to toggle the appropriate <div>
      $('#d' + id).toggle();
  })
});

使用唯一 ID 的示例

您可以 see an interactive example of this approach here并在下面演示:

enter image description here

考虑使用data-* 属性

HTML 支持使用数据属性,这些属性可用于通过 jQuery 定位特定元素并将它们与其他操作相关联。例如,如果您按如下方式在每个“p”元素上创建一个属性:

<button data-toggles='d1'>p1</button>
<button data-toggles='d2'>p2</button>
<button data-toggles='d3'>p3</button>

然后只需更改您的 jQuery 以将它们用作选择器:

$(function(){
    // When an element with a "toggles" attribute is clicked
    $('[data-toggles]').click(function(){
         // Then toggle its target
         $('#' + $(this).data('toggles')).toggle();
    });
});

关于javascript - div#d1 切换到 p#1 点击 - 如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37073757/

相关文章:

javascript - 文本区域上的智能感知插件?

javascript - 总金额显示为 NAN,javascript

java - 如何使用 JSP 和 servlet 创建类似 google 的即时搜索?

jquery - 每隔一段缩短一次文本

javascript - 尝试在更新页面后动态更改所选属性

javascript - 根据在另一个表单字段中输入的内容填充表单字段

javascript - 关于Window onload、ondomready等

javascript - 下拉菜单使文本框出现并且是必需的,不显示时则不需要

c# - 在 WinForms 桌面应用程序中使用 jQuery?

jquery - 在移动设备上使用悬停子菜单引导导航