HTML
<div class="pop-circle Cats"></div>
.CSS
.pop-circle { width:8px;height:8px;border-radius:4px;background-color:#50377A; }
.JS
$(".pop-circle").attr("title", "blah");
按预期工作。 但是,稍后(在用户交互之后(如果我 .append(mydiv( 更多具有相同"弹出圈"类的div(猫、狗等(,则不会将 title 属性添加到它们中。 这是有道理的,没有新事件。 那你会怎么做?
我的第一个想法是这样做:
$("div.pop-circle").hover( function() {
$(".Cats").attr("title", "cats");
$(".Dats").attr("title", "dogs");
// ...
});
我认为即使在加载页面后附加的div 上也应该触发悬停。 但是,这有一个奇怪的效果,没有添加属性,至少在我悬停在div 上的前几次没有,或者根本没有。 (抱歉,我不想展示附加div 的实时示例。
我想知道是否有更明智的方法来做到这一点。
对于这种情况,我会说编写一个自动向元素添加title
的函数是最好的方法。
或者,如果要使hover
工作,则必须将其绑定到文档或静态父级,然后从那里将此事件委托给div元素。
$(document).on("mouseover", ".pop-circle", function () { //or instead of document use IMMEDIATE STATIC parent
var title = $(this).attr("class").split(" ")[1]; //taking out the extra thing out of the class attribute - the animals
$(this).attr("title", title);
});
您的 HTML 现在看起来像这样:
<div class="pop-circle Cats"></div>
<br/>
<div class="pop-circle Dogs"></div>
<br/>
<div class="pop-circle Rats"></div>
<br/>
<div class="pop-circle Monkeys"></div>
<br/>
<button>Add more</button>
<input type="text" />
我添加额外.pop-circle
的代码:
$("button").on("click", function () {
var animal = $("input:text").val();
$("input:text").val("");
$(this).before("<div class= 'pop-circle " + animal + "' ></div>");
});
hover
没有按照您编码的方式工作的原因是,当您将hover
绑定到.pop-circle
时,它仅绑定到现有元素,而不是将来的元素。若要支持将来的元素,必须将此事件绑定到其父级,例如 document
或 "body"
。
这是一个演示: http://jsfiddle.net/hungerpain/zxfL2/1/
感谢@passionateCoder"将此事件绑定到其父级">
这是我最终使用的:
$("#content").on("click mouseover", ".pop-circle", function() {
$(".Dogs").attr("title", "Dog Categories");
$(".Cats").attr("title", "Cat Categories");
// ...
});
侦听器不附加到动态创建的新元素。追加代码后,需要重新注册任何事件侦听器。在函数中收集它们并再次调用它们通常很有帮助。
function ActivateListeners() {
$('div.pop-circle').hover(function() {
//do something
});
}
ActivateListeners();
$('something').click(function() {
$('body').append("<div class='pop-circle'>Stuff</div>");
ActivateListeners();
});
编辑:虽然这有效,但热情的Coder的答案(使用.on(((是处理此问题的正确方法。
根据我的理解,jQuery 中的 attr(( 方法仅获取在加载时定义的属性,并且不会包含脚本更改的值。jQuery 的 1.6 版引入了 prop(( 方法,该方法反映了在加载页面后对 DOM 所做的更改。用法是相同的。
编辑:重新阅读您的问题后,我可能会在这里偏离路线。我道歉。也许 prop(( 总有一天会派上用场!:)
您可以将数据属性添加到div,然后使用它来创建标题。
http://jsfiddle.net/pjdicke/53Yf9/1/
$("#output").on('mouseenter', '.pop-circle', function () {
var type = $(this).data('type');
$(this).attr('title', type);
alert( $(this).attr('title') );
});
$('button').on('click', function () {
var newItem = $('<div class="pop-circle" data-type="Dats"></div>');
$(newItem).appendTo('#output');
});