我想做一些文本编辑器,当单词悬停时,我可以在其中发送一些Ajax请求。页面中有代码。
<div class="word_split" contenteditable="true">Don't break my heart.</div>
有jQuery代码
$(document).ready(function () {
$(".word_split").hover(function () {
if ($(".word_split").children().length == 0) {
$(".word_split").lettering('words');
}
else {
$(".word_split").children().lettering('words');
}
});
});
$(document).ready(function () {
$(".word_split span").hover(function () {
//There'll be requests
alert("sadfsdafsa");
});
});
和CSS。
.word_split span:hover {
font-weight:bold;
}
字母仅将每个单词放在跨度的目标标签中,并在这种情况下给出类名,如word1,word2等
问题是第二个jquery函数不起作用,而Css起作用。我不明白为什么以及如何解决它。谢谢
该<span>
■不要在页面加载存在,所以事件没有挂接到任何东西。您应该on
与'mouseover'
事件一起使用,以便将来创建的元素将获得事件处理程序:
$(document).ready(function () {
$(".word_split").on('mouseover', 'span', function () {
//There'll be requests
alert("sadfsdafsa");
});
});
我看到的另一个问题是,当您运行此命令时,每次将鼠标悬停在文本上时,它将触发事件处理程序并再次拆分单词,因此最终会产生大量的空跨度-这也会触发请求。如果可能的话,最好是lettering()
直接在document
就绪状态下运行,而不是悬停运行:
$(document).ready(function () {
if ($(".word_split").children().length == 0) {
$(".word_split").lettering('words');
}
else {
$(".word_split").children().lettering('words');
}
$(".word_split").on('mouseover', 'span', function () {
//There'll be requests
alert("sadfsdafsa");
});
});
如前所述,理想情况下,所有$(document).ready
调用都应该真正进入一个调用-效率更高,并且如果没有其他操作,则您可以更好地控制执行订单代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句