gpt4 book ai didi

javascript - 由于 jQuery 脚本,类 id 无法隐藏

转载 作者:行者123 更新时间:2023-12-03 03:27:57 25 4
gpt4 key购买 nike

我希望类 z 在页面加载时隐藏,但即使它具有 display: none;

我注意到,如果我将该指令添加到包含 id xh2 中,它就会起作用!

你能帮我让它工作吗?

这是我的代码:

var data = {
shop: [{
item: "Ps3",
cost: "$150"
},
{
item: "xbox 360",
cost: "$140"
}
]
};
$(document).ready(function() {
var x = $('#x');
var output = '';
$.each(data.shop, function(index, element) {
output += element.item + '<br>' + element.cost + '<br>';
});
x.html(output);
$("button").click(function() {
x.toggle();
});
});
#x {
color: white;
text-align: center;
display: none;
}

.z {
background-color: red;
width: 250px;
margin: auto;
}
<!DOCTYPE html>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
<div class="z">
<h2 id="x"></h2>
</div>
<button>Click</button>
</body>

</html>

最佳答案

看看这是否是您想要的 - 切换 class z 而不是 id x(有关更改的说明,请参阅内联注释)

var data = {
shop: [{
item: "Ps3",
cost: "$150"
},
{
item: "xbox 360",
cost: "$140"
}
]
};
$(document).ready(function() {
var z = $('.z'); // Grab class z to toggle
z.css('display','none'); // Hide class z on load
var x = $('#x');
var output = '';
$.each(data.shop, function(index, element) {
output += element.item + '<br>' + element.cost + '<br>';
});
x.html(output);
$("button").click(function() {
z.toggle(); // Toggle z on button click
});
});
#x {
color: white;
text-align: center;
}
.z {
background-color: red;
width: 250px;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!DOCTYPE html>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
<div class="z">
<h2 id="x"></h2>
</div>
<button>Click</button>
</body>

</html>

关于javascript - 由于 jQuery 脚本,类 id 无法隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46233822/

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