简体   繁体   English

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

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

Here my jquery function is not working after the jquery ajax call. 这里我的jquery函数在jquery ajax调用之后不起作用。 here is my code 这是我的代码

Ajax call Ajax调用

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

and

<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>

and the jquery function which is not working after this ajax call is here 这个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");
        });
});

try using delegated event, as your html is coming via ajax call after the DOM load: 尝试使用委托事件,因为你的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");
        });

or can do this: 或者可以这样做:

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

Since your element created dynamically to the DOM, the events will not be available for these elements. 由于您的元素动态创建到DOM,因此这些元素将无法使用这些元素。 In this case, event delegation will help you to attach that event. 在这种情况下,事件委派将帮助您附加该事件。

Try with 试试吧

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

OR 要么

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

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

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