当我尝试从 html 字符串中的 div 获取值时遇到问题。也许这里有人可以帮我找到问题。
我尝试了很多不同的方法来取出数据。对别人有用的解决方案对我根本不起作用。所以我认为我做了一些严重错误的事情
$(document).ready(function () {
var id = 1;
function updateMsg() {
$.ajax({
url: "/opt/history/update?current=" + 1,
cache: false,
success: function (html) {
id = $(html).find('#last').html();
console.log('ID: ' + id);
$("#result").html(html);
}
});
setTimeout(updateMsg, 5000);
}
updateMsg();
});
这就是 div 的样子
<div id="last" style="display: none;">2</div>
这个div之前有一堆html代码。该 div 将始终位于 html 字符串的底部。
更新:事情是这样的。我需要在这个 html 字符串中传输 id 的值,但不以视觉方式显示它。如果你有更好的方法我应该看看。
成功时的 HTML 输出
<tr>
<td>2014-07-08 14:35:47.456</td>
<td>123</td><td>321</td>
<td>Has data</td>
<td><a data-toggle="modal" data-request="2014-07-08 14:35:47.456" data-mobile="123" data-check="321" data-log="Has latest update" data-context="Context" data-historyid="28" title="info" class="open-logInfo btn btn-default" href="#logInfo">
<i class="icon-info-sign icon-black"></i> Info </a>
</td>
</tr>
<div id="last" style="display: none;">28</div>
最佳答案
使用filter()
来实现
success: function(html){
id = $(html).filter('#last').html();
console.log('ID: ' + id);
$("#result").html(html);
}
find()
将始终搜索子元素。
编辑
您返回的 html 无效。因为div位于tr
之外。这就是为什么您的代码返回未定义的原因。要么您必须将该 div 包含在 td
中(然后您必须使用 find()
)。
或者您需要用table
包装tr
。在这种情况下,您可以使用 filter()
关于javascript - 使用jquery和ajax从html字符串中的div获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24736181/