jQuery .text()不适用于动态创建的项目,如div,span

时间:2016-08-05 05:39:32

标签: javascript jquery html

我在data.d收到了数据,但没有将数据添加到元素下面。

JS

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

HTML

我想通过id

更改此跨度的文本
<span class="btn_link" id="CountDownvote10">

2 个答案:

答案 0 :(得分:0)

你错过了包括jquery,或者你没有在document.ready()中编写你的函数来委托一个事件,它应该在框中添加文本。 检查这些问题,因为以下方法有效。

&#13;
&#13;
$(function(){
  var data = 0;
  $('input[type="button"]').click(function(){
    data++;
    $('#countUpVote').text(data);
  })
})
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分: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')); 
    }
});

希望得到这个帮助。