无法将事件附加到动态创建的html

时间:2013-12-03 12:25:20

标签: javascript jquery

我想为动态创建的元素分配一个事件,但它不起作用。 我的代码是:

$("#dvInvitar").on("click", ".spDelMail", function () {
    alert($this.html());
    $(this).remove();
});
$("#email072").bind('keypress', function (e) {
    var code = e.keyCode ? e.keyCode : e.which;
    //var id = $(this).attr("id070");
    if (code == 13) // Enter key is pressed
    {
        e.preventDefault();
        if (esMailValido($(this).val())) {
            $("#dvInvitar ul").prepend(
                '<li style="overflow: hidden;height: auto !important;height: 15px;margin: 3px;padding: 1px 3px;background-color: #eff2f7;color: #000;cursor: default;border: 1px solid #ccd5e4;font-size: 11px;border-radius: 5px;-moz-border-radius: 5px;-webkit-border-radius: 5px;float: left;white-space: nowrap;">' + '<p style="display: inline;padding: 0;margin: 0;">' + $(this).val() + '</p>' + '<span class="spDelMail" style="color: #a6b3cf;margin-left: 5px;font-weight: bold;cursor: pointer;">x</span>' + '</li>');
            $(this).val("");
        } else alert("<?=_("
        Tenés que ingresar una dirección de correo correcta ")?>");
    }
});

HTML是

<div id="dvInvitar" style="; font-size: 0.8em">
    <ul style="overflow: hidden;height: auto !important;height: 1%;width: 95%;border: 1px solid #8496ba;cursor: text;font-size: 12px;font-family: Verdana;min-height: 1px;z-index: 999;margin: 0;padding: 0;background-color: #fff;list-style-type: none;clear: left;">
        <li style="float: left;margin: 0;padding: 0;list-style-type: none;">
            <input id="email072" type="text" style="outline: none;width: 30px;border: 0;width: 100px;padding: 3px 8px;background-color: white;margin: 2px 0;-webkit-appearance: caret;" />
        </li>
    </ul>
</div>

2 个答案:

答案 0 :(得分:1)

您需要使用委托选择器,就像使用.spDelMail元素一样。试试这个:

$(document).on('keypress', "#email072", function(e) {
    // rest of your code...
}

答案 1 :(得分:0)

有效。在第一行有一个错误,它说$ this需要说$(this)