3

我正在尝试从 Ajax 请求的 responseText 中附加 ap 元素。

在追加之前,我想看看 responseText 是否已经存在于父 div 元素文本中,如果是这样,就不要添加它。问题是我无法使用变量 responseText 让 indexOf(responseText) 工作。当我将字符串文字传递给 indexOf 时,我的代码有效。

这是我的代码:

jQuery('#addButton').live('click', function () {

    new Ajax('<url>', {
        method: 'get',
        dataType: 'html',
        onSuccess: function (responseText) {
            var text = jQuery('#div').text();

            if (text.indexOf(responseText) == -1) {
                //always true using responseText; 
                //string literal works though
                jQuery('#div').append(responseText);
            }
        }
    }).request();

})

在此先感谢您的任何建议。

4

3 回答 3

3

也许是因为您正在寻找纯文本中的 html。尝试使用html而不是text

var text = jQuery('#div').html();
if (text.indexOf(responseText) == -1) {
   ...
于 2010-07-16T19:33:26.053 回答
1

用 jQuery 包装响应并尝试与text()它的表示进行比较...

var resp = $(responseText);
var div = $("#div");

if(div.text().indexOf(resp.text()) == -1)
  resp.appendTo(div)
于 2010-07-16T19:35:47.357 回答
0

上面没有解决方案对我有用(jQuery 1.11.2)。

但我终于找到了我的解决方案:$(my_variable).selector

它对我来说没有问题:

var responseText = "word";
var resp = $(responseText).selector;



$("div").each(function() {
  if ($(this).text().indexOf(resp) >= 0) {
    alert("I've found your query: " + resp + " at " + $(this).offset().left + "/" + $(this).offset().top);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>THis is a test</div>
<div>I'm searching for this word</div>
<div>nothing here</div>

于 2015-10-25T05:35:43.610 回答