2016-08-05 25 views
-2

我收到的數據是data.d,但它不會將數據添加到下面的元素。jQuery .text()不適用於動態創建的項目,如div,span

JS

$("#CountUpvote").text(data.d); 

HTML

我想通過ID來改變這種跨度的文本

<span class="btn_link" id="CountDownvote10"> 
+1

提供您的html和這裏的js代碼 –

+1

顯示data.d或數據 – guradio

+0

我想通過ID來改變這種跨度的文本的 Downvote

回答

0

要麼你錯過了包括jQuery的,或者你不寫你在document.ready()中委託一個事件,在該事件上它應該將文本添加到框中。 檢查這些問題,因爲下面的方法有效。

$(function(){ 
 
    var data = 0; 
 
    $('input[type="button"]').click(function(){ 
 
    data++; 
 
    $('#countUpVote').text(data); 
 
    }) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type = "button" value="upvote" /> 
 
<div id="countUpVote"> 
 

 
</div>

0

正如你提到的,您可以動態創建一些元素,也data.d意味着你必須ajax調用,因此在一般情況下,你需要做的是這樣的:

$.ajax({ 
    // the parameters for making ajax working 
    success: function(responseFromServer){ 
     // for creating element using `jQuery` you have 2 options 
     // option #1: 
     $('<div />', { 
      text: responseFromServer.SOME_DATA, 
      // you can add class, css, ... to `div` here 
     }).appendTo($('SOME_ELEMENT')); 

     // option #2 
     $('<div />') 
      .text(responseFromServer.SOME_DATA) 
      .addClass('my-class') 
      .appendTo($('SOME_ELEMENT')); 
    } 
}); 

希望得到這個幫助。