gpt4 book ai didi

php - 当 jquery 用于自动刷新时创建的附加

转载 作者:行者123 更新时间:2023-11-28 05:39:34 25 4
gpt4 key购买 nike

我有 3 个 div,在 div 上有 3 个不同的背景和文本打印。每当 response.php 中的内容被修改时,每个 block 上的文本都会自动刷新。

问题
如屏幕截图所示,创建了另外 2 个 div

目标
我想删除额外的 div

我的代码:

CSS

#container{
width:50px;
height:50px;
background:cornflowerblue;
color:white;
}
#container2{
width:50px;
height:50px;
background:black;
color:red;
}
#container3{
width:50px;
height:50px;
background:brown;
color:yellow;
}

JS/jQuery

 $(document).ready(function() {
$("#container").load("response.php");
var refreshId = setInterval(function() {
$("#container").load('response.php');
}, 1000);

$("#container2").load("response.php");
var refreshId = setInterval(function() {
$("#container2").load('response.php');
}, 1000);

$("#container3").load("response.php");
var refreshId = setInterval(function() {
$("#container3").load('response.php');
}, 1000);
$.ajaxSetup({ cache: false });
});

HTML

<body>
<div id="container"></div><p>
<div id="container2"></div><p>
<div id="container3"></div>
</body></html><p>

response.php

 <?php  
echo '<div id="container">1</div>';
echo '<div id="container2">2</div>';
echo '<div id="container3">3</div>';
?>

可以做些什么来实现我的目标?我使用 jQuery 的方式是否正确?

enter image description here

最佳答案

这是预期的行为。 response.php 包含 3 个 div,您将加载 3 次。
因此 3 * 3 = 9。

可能是另一种方式,而不是在加载 php 文件时加载 3 个 div。只有 1。但是,我意识到您无法设置 id,因为 ID 是唯一的。相反,您可以为它们提供 class 属性(即 class="container")。然后,您就可以使用 :nth-child() 通过 jQuery 选择单个子项。例如,如果你想选择/引用第二个 div,你可以说:(在 jQuery 中)

$(".container:nth-child(2)").on('click', function() {
// do stuff
});

关于php - 当 jquery 用于自动刷新时创建的附加 <div>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37988615/

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