gpt4 book ai didi

javascript - 使用动态创建的 DOM 元素在单击时添加样式

转载 作者:太空宇宙 更新时间:2023-11-04 01:44:51 25 4
gpt4 key购买 nike

我想在选中 div 时围绕包含在 div 中的图像创建边框,然后在取消选中时将其移除。如何获取所选 div 的 ID?

 function displayLive()
{
var previous = null;
var current = null;
setInterval(function()
{
$.ajax({
url: '/showLive',
dataType: 'json',
contentType: 'application/json',
success: function(response)
{
current = JSON.stringify(response);
if(previous !== current)
{
var obj = JSON.parse(response);
console.log(obj);
for(var i = 0; i < obj.active.length; i++)
{
if($(document.getElementById(obj.active[i].userNameData)).length == 0)
{
if(obj.active[i].active === true)
{
$('.left').prepend($('<div/>', {class: 'profTemp', id: obj.active[i].userNameData}).append(
$('<img/>', {src: obj.active[i].profiler, width: 40, height: 40}),
$('<span/>', {text: " " + obj.active[i].userNameData})));
}

}
else if(obj.active[i].active === false)
{
$(document.getElementById(obj.active[i].userNameData)).remove();
console.log("getting in false");
}
}
}
}
});
previous = current;
}, 2000);
}

here'a a template

最佳答案

通过 $(document).on('click', '.profTemp', function() {}) 分配点击处理程序以触发文档上的点击事件,以便它可以与动态添加元素,然后在 div 上切换一个类,并将其用作是否被单击的状态,并引用该类来绘制边框。

$('body').append('<div class="profTemp">  <img class="img" src="/image/2C22p.jpg"></div>');

$(document).on('click','.profTemp',function() {
$(this).toggleClass('selected');
})
.profTemp {
display: inline-block;
}
.selected img {
border: 5px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 使用动态创建的 DOM 元素在单击时添加样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44765203/

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