【问题标题】:JQuery use .replaceWith() on html element that was created using previous .replaceWith()JQuery 在使用以前的 .replaceWith() 创建的 html 元素上使用 .replaceWith()
【发布时间】:2015-09-15 15:33:24
【问题描述】:

我正在开发一个包含大量空白 div 标签的简单网页

<div></div>

在我的 css 中,我将 div 设置为 100 像素 x 100 像素的正方形,并带有背景颜色。

我正在使用 jQuery 让鼠标通过更改颜色与 div 交互,当单击时,div 在原始正方形的空间内分解为四个较小的正方形。较小的方块是使用 .replaceWith() 调用创建的。这一切都很好。

我的问题是,如果我单击其中一个较小的方块,我希望它在其位置上再替换四个较小的方块,但它什么也没做。

这是我的 jQuery

$(document).ready(function(){

$(document).on('mouseover', 'div', function(){
    $(this).css("background-color", "#4499FF");

    $(this).mouseleave(function(){
        $(this).css("background-color", "#2277AA");
    });

});

$(document).on('click', 'div', function(){
    $(this).replaceWith('<div><div class="small"></div><div class="small"></div><div class="small"></div><div class="small"></div></div>');
});
$(document).on('click', '.small', function(){
    $(this).replaceWith('<div><div class="small"></div><div class="small"></div><div class="small"></div><div class="small"></div></div>');
});

});

我的 css 有一个 .small{},宽度和高度设置为 50%,所以根据定义,我相信它应该可以工作。

【问题讨论】:

  • 这是我第二次遇到轻量级代码来生成和操作&lt;div&gt; 标签。我认为这是一个很好的概念。这是我第一次遇到它的链接。 jsfiddle.net/rxa60aj6

标签: javascript jquery html css


【解决方案1】:

我认为您不需要.replaceWith。你可以简单地使用.append。此外,由于.small&lt;div&gt;,它将触发both 文档点击处理程序,这似乎不是预期的行为。此外,通过在 mouseover 事件中绑定 mouseleave 事件,您可以为每个 div 绑定多次。

我建议仅在最里面的 &lt;div&gt; 元素上启用鼠标悬停事件,并改用 append:

// Split into 2 events
// Use :not(:has(div)) to ensure that the div has no children
$(document).on('mouseover', 'div:not(:has(div))', function () {
    $(this).css("background-color", "#4499FF");
});
$(document).on('mouseleave', 'div:not(:has(div))', function () {
    $(this).css("background-color", "#2277AA");
});

$(document).on('click', 'div', function (e) {
    // Only append the elements to the target element clicked
    // This prevents unwanted behavior when clicking a div inside a div.
    if (e.target == this) {
        $(this).append('<div class="small"></div><div class="small"></div><div class="small"></div><div class="small"></div>');
    }
});

Example Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    相关资源
    最近更新 更多