gpt4 book ai didi

javascript - 如何动态操作 HTML 中的元素

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

我有一个预定义的 div 和相应的 CSS 如下:

<div id="pin0" style="display: none" class="pin">
<div class="comment">
<div class="delete">
<a href="javascript:void(0);" onclick="deletePin(this);">
<img src="/Images/RE/cross.png" style="border: 1px groove" width="16px" height="16px" /></a>
</div>
<textarea style="border: 0px; resize: both;" rows="3" cols="35" placeholder="Comment"></textarea>
</div>
</div>
<img src="/Images/RE/03.png" />

.pin
{
position: absolute;
background-image: url('/Images/RE/ping.png');
width: 32px;
height: 16px;
z-index: 999;
}

.delete
{
position: relative;
top: 0px;
left: 0px;
background-color: transparent;
width: 300px;
text-align: right;
}

.comment
{
position: absolute;
top: 100%;
left: auto;
}

这将是结果:

enter image description here

请注意,整个 DIV 是一个隐藏元素,然后允许用户通过 JQuery 双击克隆它们,如下所示:

$("#clicks").dblclick(function (e) {
var offset_t = $(this).parent().offset().top - $(window).scrollTop();
var offset_l = $(this).parent().offset().left - $(window).scrollLeft();

var newX = Math.round((e.clientX - offset_l));
var newY = Math.round((e.clientY - offset_t));

var newDiv = $('#pin0').clone();
newDiv.attr('id', 'pin' + $("#clicks").children('.pin').length);

$(newDiv).css('top', newY - 25);
$(newDiv).css('left', newX - 10);
$(newDiv).css('display', 'block');

$(this).append(newDiv);
$(newDiv).draggable();
}
)

如您所见,我通过 'pin' + $("#clicks").children('.pin').length 设置了 ID。现在我想知道如何动态地操作这个特定元素。我已经通过如下硬编码 ID 尝试了非常手动的方式,但根本不起作用:

$("#pin1").focus(function (e) {
alert("hello!");
})

最佳答案

使用.on()

由于您的内容是动态添加的,因此无法直接访问,因此您必须使用事件委托(delegate)。

$("#clicks").on('focus','#pin1',function (e) {
alert("hello!");
});

根据 OP 的评论更新

当你点击图片时会有提示

$("#clicks").on('click','#pin1 img',function (e) {
alert("hello!");
});

当您点击以 pin

开头的 id 中包含的图像时,将发出警报
$("#clicks").on("focus", "[id^=pin] img", function (e) {
alert("hello!");
});

提醒ID

$("#clicks").on("focus", "[id^=pin]", function (e) {
alert(this.id);
});

或者用 img

$("#clicks").on("focus", "[id^=pin] img", function (e) {
alert($(this).closest("[id^=pin]").attr("id"));
});

关于javascript - 如何动态操作 HTML 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19090551/

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