这是我的HTML结构。

<div id="dvHirearachy" class="MarginTB10">
    <span>
        <label>Hierarchy Names</label><br />
        <input type="text" name="txtHierarchy" />
        <a id="ancRemove" href="#">Remove</a>
    </span><br />
    <a id="ancNew" href="#">New Hierarchy Name</a>
</div>


在单击锚标记“ ancNew”时,我再次生成标记中提到的完整跨度标记。

问题是在单击文本框时也会生成跨度结构。我在单击“ ancRemove”时遇到相同的问题,因为我试图停止事件冒泡,它已对此起作用,但不适用于文本框。

我的剧本

 $(document).ready(function () {

            $("#ancRemove").click(function (e) {
                RemoveHierarchy(this, e);
            });

            $("#ancNew").click(function (e) {
                generateNewHierarchy(e);
            });
});
 function generateNewHierarchy(e) {
            if (window.event) {
                var e = window.event;
                e.cancelBubble = true;
            } else {
                e.preventDefault();
                e.stopPropagation();
                var container = createElements('span', null);
                $(container).append(createElements('input', 'text'));
                $(container).append(createElements('a', null));
                $(container).append("<br/>").prependTo("#ancNew");
                $(container).children('input[type=text]').focus();
            }
        }

        function createElements(elem,type) {
            var newElem = document.createElement(elem);

            if (type != null) {
                newElem.type = "input";
                newElem.name = "txtHierarchy";
                $(newElem).addClass('width_medium');
            }

            if (elem == "a") {
                newElem.innerHTML = "Remove";
                $(newElem).click(function (e) {
                    RemoveHierarchy(this,e);
                });
            }
            return newElem;
        }

        function RemoveHierarchy(crntElem, e) {
            e.stopPropagation();
            $(crntElem).parents("span:first").remove();
        }


如何避免这种情况。

最佳答案

检查这个jsfiddle:

http://jsfiddle.net/xemhK/

问题是prepandTo语句,它是预填充#ancNew锚标记中的元素,这就是为什么所有文本框和删除锚都传播#ancNew的click事件的原因,并且它正在调用generateNewHierarchy()函数。

$(container).append("<br/>").prepandTo("#ancNew");更改为$(container).append("<br/>").insertBefore("#ancNew");

function generateNewHierarchy(e) {
    if (window.event) {
        var e = window.event;
        e.cancelBubble = true;
    } else {
        e.preventDefault();
        e.stopPropagation();
        var container = createElements('span', null);
        $(container).append(createElements('input', 'text'));
        $(container).append(createElements('a', null));

        //$(container).append("<br/>").prepandTo("#ancNew");
        $(container).append("<br/>").insertBefore("#ancNew");

        $(container).children('input[type=text]').focus();
    }
}


和在createElements中

if (elem == "a") {
    newElem.innerHTML = "Remove";
    $(newElem).attr("href","#").click(function (e) {
        RemoveHierarchy(this,e);
    });
}

07-24 17:43