繁体   English   中英

如何动态操作HTML中的元素

[英]How to dynamically manipulate elements in HTML

我有一个预定义的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;
    }

这将是结果:

在此输入图像描述

请注意,整个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 'pin' + $("#clicks").children('.pin').length 现在我想知道如何动态操纵这个特定的元素。 我通过硬编码ID尝试了非常手动的方式,如下所示,但根本不工作:

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

使用.on()

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

$("#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!");
});

提醒身份

$("#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"));
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM