[英]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.