簡體   English   中英

jQuery 在 ajax 之后不更改元素文本

[英]jQuery does not change element text after ajax

我有以下 html:

 <div class="form-outline mb-4">
      <input type="text" id="PlanID" asp-for="PlanID" name="PlanID" class="form-control form-control-lg" value="@Model.PlanID" />
      <label id="errorLabel" name="errorLabel" class="form-label text-danger" for="PlanID"></label>
 </div>
 <button class="btn btn-primary btn-lg btn-block" type="button" disabled id="nextButton" name="nextButton" onclick="DisplayProgressMessage(this, 'Next');">Next</button>

我有以下 jquery:

 $.ajax({
      type: "POST",
      url: "@Url.Action("CheckPlanID")",
      data: {PlanID: planID},
      dataType: "text",
      success: function (msg) {
      if (msg.length > 4) {
           console.log(msg.length);
           $("#nextButton").prop("disabled", true);
           $("#errorLabel").text = msg;
      }
      },
      error: function (req, status, error) {
                console.log(msg);
      }
 });

我還有額外的 jquery 使按鈕保持禁用狀態,直到輸入中的數據長度為 4。當長度為 4 時,我啟用按鈕。

運行代碼時,只要輸入框中的數據長度為4,按鈕就被啟用,我點擊它。 ajax 執行並將數據發送到我的 controller。 controller 處理數據並將返回一個字符串。 如果返回字符串的長度大於 4,則返回的字符串是錯誤字符串,並且該錯誤字符串應該顯示給用戶。

當我運行代碼並強制出錯時,我可以看到控制台中顯示的錯誤字符串的長度,因此我知道這部分代碼正在執行。 該按鈕被禁用,但 errorLabel 的文本沒有改變。

errorLabel 的文本應更改為錯誤消息。 還有什么需要做的嗎? 我錯過了什么嗎?

謝謝!

jQuery中, text是一種方法而不是屬性,因此要解決您的問題,您只需更改它

$("#errorLabel").text = msg

進入這個

$("#errorLabel").text(msg)

此外,根據您的代碼if (msg.length > 4) ,您似乎只在msg長度大於4時更改文本。 這意味着,除非msg5或更多字符,否則文本不會改變。

jQuery文檔上了解有關text()方法的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM