我有這個 ajax 函式,它應該改變單擊按鈕的樣式,但由于某種原因它不起作用。我在控制臺中沒有收到任何錯誤,并且 ajax 呼叫成功知道這里有什么問題嗎?
function AcceptOffer(id)
{
var json = {
id : id
};
$.ajax({
type: 'POST',
url: "@Url.Action("AcceptOffer", "Product")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function() {
$(this).text("Accepted");
$(this).css("background-color", "green");
$(this).css("color", "white");
$(this).attr('disabled', true);
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
}
</script>
html:
<a href="javascript:void(0)" onclick="AcceptOffer('@item.OfferId')" class="btn btn-default acceptbtn">Accept</a>
uj5u.com熱心網友回復:
您的問題是使用this不正確。您使用它的方式,它將參考您傳遞給 ajax 命令的物件
function AcceptOffer(id)
{
var json = {
id : id
};
var elemYouWantToChange =...;
$.ajax({
type: 'POST',
url: "@Url.Action("AcceptOffer", "Product")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function() {
$(elemYouWantToChange).text("Accepted");
$(elemYouWantToChange).css("background-color", "green");
$(elemYouWantToChange).css("color", "white");
$(elemYouWantToChange).attr('disabled', true);
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
}
- 編輯 -
在 javascript 中,您會聽到這樣的點擊:
elem.addEventListener('click', function(e) {
console.log(e.target); // You need to get e.target to AcceptOffer so it can style the correct element
AcceptOffer(...);
});
uj5u.com熱心網友回復:
在您的代碼this中沒有指向錨標記,您只需要傳遞this對您的函式的參考。
function AcceptOffer(ele, id)
{
var json = {
id : id
};
$.ajax({
type: 'POST',
url: "@Url.Action("AcceptOffer", "Product")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function() {
$(ele).text("Accepted");
$(ele).css("background-color", "green");
$(ele).css("color", "white");
$(ele).attr('disabled', true);
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
}
所以錨標記將是:
<a href="javascript:void(0)" onclick="AcceptOffer(this, '@item.OfferId')" class="btn btn-default acceptbtn">Accept</a>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/475828.html
標籤:javascript jQuery
