1

I'm making a code where I add content dynamically by appending an ul element.

The thing is that if I click the dynamically created button called savePalette it doesn't work.. Although it does work for the first one, because I define the addPalette function before the click function..

From what I have read, .on() is supposed to work in these cases where dynamic content is added.

This is the HTML Structure:

<ul class="palettes">
    <li class="paletteGroup">
        <ul>
            <li class="colorpalette" style="background-color: #00c4ff;"></li>
            <li class="colorpalette" style="background-color: #00a6ff;"></li>
            <li class="colorpalette" style="background-color: #0091ff;"></li>
            <li class="colorpalette" style="background-color: #007bff;"></li>
            <li class="paletteControls">
                <button name="savePalette" class="savePalette">Save</button>
                <button name="changeName" class="changeName">Change Name</button>
            </li>
        </ul>
    </li>
</ul>

JavaScript:

function addPalette() {
        var defaultColors = ["#00c4ff", "#00a6ff", "#0091ff", "#007bff"];

        $("ul.palettes").append("<li class=\"paletteGroup\"><ul>" +
        "<li class=\"paletteControls\"><button name=\"savePalette\" class=\"savePalette\">Save</button>" +
        "<button name=\"changeName\" class=\"savePalette\">Change Name</button></li>" +
        "</li></ul></li>");
        $("li.paletteGroup:last").hide();

        for(var i = 1; i <= 4; i++) {
            var j = (4 - i);
            $("ul.palettes li.paletteGroup:last ul").prepend("<li class=\"colorpalette\" style=\"background-color:" + defaultColors[j] + "\"></li>");
        }

        $("li.paletteGroup").show("fade", 500);
    }

And then this at the top of the script tag

addPalette();

$("button[name=savePalette]").on("click", function() {
    alert("Heeeeej");
});
4

4 回答 4

7

您必须将动态元素的选择器放在选择器参数中:

$("ul.palettes").on("click", "button[name=savePalette]", function() {
    alert("Heeeej");
});
于 2013-10-01T17:09:41.723 回答
2

on()仅在委托时才与动态元素一起使用:

$("ul.palettes").on("click", "button[name=savePalette]", function() {
    alert("Heeeeej");
});
于 2013-10-01T17:09:21.473 回答
1

由于它是动态创建的,因此.on()需要更广泛的范围:

$('body').on("click", "button[name=savePalette]", function() {
    alert("Heeeeej");
});

现在代码将监听在始终存在button[name=savePalette]的标签内被点击。<body>

如果您正在动态添加ul.palettes它的所有子元素,那么您将希望在主体内而不是在ul

于 2013-10-01T17:10:02.620 回答
1

它怎么对我有用?哦,是的,而不是使用

$("li.paletteGroup").show("fade", 500);

利用: $("li.paletteGroup").fadeIn();

看到这个jsFiddle

于 2013-10-01T17:23:49.467 回答