簡體   English   中英

無法用jQuery更改按鈕的html

[英]Can't change html of button with jQuery

我只是想改變按鈕內的html。 我以前做過但是我的jQuery版本有問題或者我錯過了什么。 無論哪種方式,這都很奇怪,因為它適用於應用程序中的許多其他位置。

當我點擊一個按鈕時我發射的事件,事件工作正常,但我也試圖改變按鈕的外觀,正如之前說的那樣,我的應用程序中的每一個都在這里工作。

這不是很多代碼:

var listButton = $('#list-button');
console.log(listButton); // Shows the correct one, this is the button I want
listButton.html('test') // This does nothing, the appearance doesn't change

然而,當我這樣做時,這是最奇怪的部分:

var listButton = $('#list-button');
console.log(listButton.get(0));
listButton.html('test')
console.log(listButton.get(0));

console.log()都顯示按鈕,好像html已更改,甚至在我更改html之前。 而且,可見按鈕沒有變化。 以前有沒有人經歷過這樣的事情,我只是錯過了一些非常明顯的東西,或者這里有什么不妥之處? 另外,我在整個項目中只有一個#list-button。 就好像在這個特定的文件中,“var listButton = $('#list-button')”只是創建一個“深層”副本而沒有與真實html元素的實際連接。

所有這些都是在Backbone View中用Javascript編寫的。

編輯:這是用於包含按鈕的標題的html模板

<div class="item-list-header">
  <button id="select-all-button" class="item-editor-toolbar-button items-header-button">Select all</button>
  <button id="export-button" class="item-editor-toolbar-button items-header-button">Export Selected</button>
  <button id="refresh-button" class="item-editor-toolbar-button items-header-button">Refresh</button>
  <center>
    <button id="list-button" class="item-editor-toolbar-button items-header-button">
      <i class="fa fa-bars" style="margin-right: 10px;"/>List
    </button>
  </center>
</div>

很容易解決

 $("#listButton").click(function(){ alert("This button works"); $(this).html('test') }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <button id="listButton"> The Button </button> 

Stryner的回答很明顯。 我只有一次id="list-button"但由於某種原因我添加了包含該按鈕兩次的模板。 但是看不到另一個。 更改html更改了第一個,因此更改在頂部的那個上不可見。

對我有用。

HTML

<button id='list-button' type='button'>Add</button>

JS

$("#list-button").html('Save');

可能是,你使用type="button"input標簽,在這種情況下你應該使用它。

HTML

<input type='button' value='Add' id='list-button'>

JS

$("#list-button").prop('value', 'Save');

要么

$("#list-button").attr('value', 'Save');

暫無
暫無

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

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