繁体   English   中英

如何通过JQuery从HTML元素获取实时数据?

[英]How to get live data from HTML element by JQuery?

元件

<span class="bar">xxx</span>

包含值,并由Ajax更新。

我已经使用此脚本通过JQuery成功地将此xxx数据获取为变量

var foo = $('.bar').html();
$("#other").append("<strong>" + foo  + "</strong>");
// alert(foo) <- for testing

将其附加到页面中的#other位置,效果很好,但是...如何从此.bar元素获取实时数据(由Ajax更新)?

您可以使用以下内容:

$('.bar').bind("DOMSubtreeModified",function(){
  $("#other strong").text($(this).text());
});

修改.bar时,它将更新#other strong 又名,当其更新。

 var foo = $('.bar').text(); $("#other").append("<strong>" + foo + "</strong>"); $("button").click(function() { $('.bar').text("new data"); }) $('.bar').bind("DOMSubtreeModified",function(){ $("#other strong").text($(this).text()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="bar">xxx</span> <div id="other"></div> <button>add new content to bar</button> 

使用.on(),因为.bind()已弃用!

 // to simulate ajax changing contents $('.ajax').on('keyup', function(){ $('.first_div').html($(this).val()) }) // your answer updater(); $('.first_div').on('DOMSubtreeModified', updater) function updater(){ var data = $('.first_div').html(); // your logic here data = '[' + data + ']' // display result $('.second_div').html(data) } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <pre> Enter new content: <input class="ajax" value="initial"> This is what ajax updates: <div class="first_div">initial</div> This is updated by DOMSubtreeModified event: <div class="second_div"></div> </pre> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM