这里我的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");
});
});
答案 0 :(得分:1)
尝试使用委托事件,因为你的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");
});
答案 1 :(得分:1)
由于您的元素动态创建到DOM,因此这些元素将无法使用这些元素。在这种情况下,事件委派将帮助您附加该事件。
尝试
$(".commentContainer").on('focus','.inputcomment',function () {
OR
$(document).on('focus','.inputcomment',function () {