这是我的 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>
单击 anchor 标记“ancNew”时,我将再次生成上面标记中提到的完整 span 标记。
问题出在单击文本框时也会生成 span 结构。我在点击“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 anchor 标记中预填充元素,这就是为什么所有文本框和删除 anchor ,都在传播 #ancNew 的点击事件,它正在调用 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);
});
}
关于javascript - 单击文本框事件冒泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11608566/