繁体   English   中英

jquery在ajax post asp.net mvc4之后无法正常工作

[英]jquery not working after ajax post asp.net mvc4

这里我的jquery函数在jquery ajax调用之后不起作用。 这是我的代码

Ajax调用

 <input type="button" value="Comment" class="submitComment" onclick="AddItem(this);" />

<script type="text/javascript">
     function AddItem(data) {        
            postData = $(data).parents().find("textarea");
            var input = { "PrdHierKey": postData.parents().find('input[data-attr="ProdKey"]').val(),
                "GeoHierKey": postData.parents().find('input[data-attr="GeoKey"]').val(),
                "Period": postData.parents().find('input[data-attr="Period"]').val(),
                "Comment": postData.val()
               };
            $.ajax({
                url: '@Url.Action("AddComments", "Card")',
                type: "POST",
                data: JSON.stringify(input),
                cache: false,
                contentType: 'application/json; charset=utf-8',
                success: function (result) {
                    $(".commentContainer").html(result);
                }
            });


        }
</script>

这个ajax调用之后没有工作的jquery函数就在这里

$(document).ready(function () {
     $(".inputcomment").focus(function () {        
            $(this).css("height", "50px");
            if ($(this).val() == "Add a comment") {
                $(this).val("");
            }
            $(".submitComment").show();
            $(this).addClass("inputActive");
        });
});

尝试使用委托事件,因为你的html是在DOM加载后通过ajax调用来的:

 $(document).on('focus','.inputcomment',function () {        
            $(this).css("height", "50px");
            if ($(this).val() == "Add a comment") {
                $(this).val("");
            }
            $(".submitComment").show();
            $(this).addClass("inputActive");
        });

或者可以这样做:

$('.commentContainer').on('focus','.inputcomment',function () {        
                $(this).css("height", "50px");
                if ($(this).val() == "Add a comment") {
                    $(this).val("");
                }
                $(".submitComment").show();
                $(this).addClass("inputActive");
            });

由于您的元素动态创建到DOM,因此这些元素将无法使用这些元素。 在这种情况下,事件委派将帮助您附加该事件。

试试吧

$(".commentContainer").on('focus','.inputcomment',function () {

要么

$(document).on('focus','.inputcomment',function () {  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM