2014-07-14 34 views
0

我尝试从我的html字符串中的div中获取值时出现问题。也许这里有人可能会为我找到问题。从jquery和ajax的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的值,但不能直观地显示它。如果你有更好的办法,我应该看看。

成功

<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> 
+0

'我有一个问题,当我尝试从我的html字符串中的一个div中获取值。“什么问题? – Nivedita

+0

当我尝试console.log的id值。对于我试过的所有内容,它是空的或未定义的 –

+0

您可以在成功回调中提供'console.log(html)'输出。 – PeterKA

回答

3

使用filter() HTML输出它

success: function(html){ 
       id = $(html).filter('#last').html(); 
       console.log('ID: ' + id); 
       $("#result").html(html); 
      } 

find()将始终搜索子元素。

编辑

你返回的HTML是无效的。因为div在tr之外。这就是为什么你的代码返回undefined。要么你必须将该div包含在td之内(那么你必须使用find())。

Fiddle using find()

,或者您需要一个table包裹tr。在这种情况下,你可以使用filter()

Fiddle using filter()

+0

我已尝试过滤器。不知怎的,仍然得到undefined –

+0

你能告诉我们返回的HTML吗? –

0

而不是寻找( '#last'),可以直接访问它

id = $('#last').html(); 
+0

不,他不能,HTML不包含在DOM中 –

+0

这会在DOM中查找,对不起。 – PeterKA

0

首先,您需要只插入这个HTML DOM进入,然后你可以用jQuery来搜索你的#last div。例如。

function updateMsg() { 
    $.ajax({ 
     url: "/opt/history/update?current=" + 1, 
     cache: false, 
     success: function(html){ 
      $("#result").html(html); 
      id = $("#result #last").text(); 
      console.log('ID: ' + id); 
     } 
    }); 
setTimeout(updateMsg, 5000); 
} 
+0

将它添加到HTML是一个坏主意。这是污染DOM,并采取额外的果汁来清洁它。 –

+0

我现在试过这个。 日志不给我任何价值。它像id是一个空字符串 –

0

尝试这种解决方案:

我认为这是DOM结构的问题,所以试图通过表标签包围你的HTML。

 $(document).ready(function(){ 
     var id = 1; 

     function updateMsg() { 
     $.ajax({ 
     url: "/opt/history/update?current=" + 1, 
     cache: false, 
     success: function(html){ 
      var html1= "<table>"+html+" </table>"; 
     var jqObj=$('<div>',{html:html1}); /// here is the trick 
      id = jqObj.find('#last').html(); 
      console.log('ID: ' + id); 
      $("#result").html(html); 
     } 
    }); 
setTimeout(updateMsg, 5000); 
} 

updateMsg(); 
     }); 
+0

日志告诉我,当我尝试这一个出来时,id是undefined –

+0

@Jemil Riahi我试过了,它的工作原理非常完美!请console.log(html),让我看看它 – mehsen

+0

我有console.log(HTML)上面。 –