gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:59:24 24 4
gpt4 key购买 nike

我试图在单击名称时切换 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com