【问题标题】:jquery event not firing for html generated from jquery templatejquery 事件未针对从 jquery 模板生成的 html 触发
【发布时间】:2012-11-29 13:16:41
【问题描述】:

我对 Jquery 有点陌生,遇到了这个问题。

这是我的 JavaScript

$(document).ready(function () {

    $("input.selected").change(function () {

        var cbid = $(this).attr('id');

        var id = cbid.substring(3);

        var base = window.location.host;

        if ($(this).is(':checked')) {
            $.ajax({
                type: "Get",
                url: "/api/SPChoices/" + id,
                success: function (data) {
                    alert("Choice succesfully saved.");
                },
                error: function (data) {
                    alert("This user cannot be added.");
                }
            });
        }
        else {
            $.ajax({
                type: "Delete",
                url: "/api/SPChoices/" + id,
                success: function (data) {
                    alert("Choice succesfully removed." + data);
                },
                error: function (data) {
                    alert("This user cannot be deleted");
                }
            });

        }
    });

    $.ajax({
        type: "Get",
        url: "/api/SPChoices",
        data: "{'Count':'7'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            ApplyTemplate(msg);
        }
    });



});

同时应用模板生成代码的html。生成正确。

function ApplyTemplate(msg) {

    $("#HBsTemplate").tmpl(msg).appendTo("#Container");

}

</script>

<script id="HBsTemplate" type="text/x-jquery-tmpl"> 
<div>
            <div style=" float:left">
            <img id="imgChooseHBpp" src="/Images/2.png" alt="alt text" />
            </div>
            <div>
                <h3>${HostedBuyer.Name}</h3>
                <p>templ</p>
                <input class='selected' type='checkbox' {{if IsSelected}}         checked="yes" {{/if}}   id='cb_${HostedBuyer.id}' />
            </div>
</div>
</script>

我的问题是更改复选框不会触发事件。

如果我在服务器上的razor 中生成上面的html,它可以正常工作,但当我像上面那样在客户端生成时不能正常工作?

我错过了什么?请帮忙。

提前致谢。

【问题讨论】:

    标签: jquery razor asp.net-mvc-4 jquery-templates


    【解决方案1】:

    必须使用 jQuery 的 .on() 功能才能连接在加载时不发生的事件。

    【讨论】:

    • 对不起,我没听懂。
    • $().change 适用于现有元素。 $().on 适用于所有元素,甚至是动态加载的元素,您的模板系统就是这种情况。
    • 现在你的答案只对了一半。 .on() 结合了委托式事件和普通事件。这取决于参数。
    • 甚至 $().on 仅适用于已生成的标记,但不适用于动态生成的控件。我已经通过在模板标记中添加 onchange="changefunction(event) for 解决了这个问题。谢谢大家的回答。
    猜你喜欢
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多