1

当用户将鼠标悬停在特定的文本字符串上时,我正在使用jquery hovercard 插件从使用 ajax 的文本文件中提取文本 - 这一切都很好,(下面的代码)。

现在我想做的是在文本文件中有许多不同的 div(如下所示),并根据悬停在哪个文本字符串上拉入相关的 div。这对 Jquery/Ajax 是否可行,如果可以,请问您是如何做到的?

//文本文件内容

<div id="John_Resig">
<div class="contact">John Resig</div>
<p><strong>Testing testing testing!</strong></p>
<p>And on another line of text : )</p>
</div>

<div id="Tim_Berners_Lee">
<div class="contact">Tim Berners-Lee</div>
<p><strong>Testing testing testing!</strong></p>
<p>And on another line of text : )</p>
</div>

//jQuery/Ajax 代码

$(document).ready(function () {
var hoverHTMLDemoAjax = '<div class="demo-cb-tweets"></div>';
$(".demo-ajax").hovercard({
    detailsHTML: hoverHTMLDemoAjax,
    width: 350,
    delay: 500,
    cardImgSrc: 'http://ejohn.org/files/short.sm.jpg',
    onHoverIn: function () {
        $.ajax({
            url : "helloworld.txt",
            type: 'GET',
            dataType: "text",
            beforeSend: function () {
                $(".demo-cb-tweets").prepend('<p class="loading-text">Loading latest tweets...</p>');
            },
            success: function (data) {
                $(".demo-cb-tweets").empty();
                $(".demo-cb-tweets").html(data);
            },
            complete: function () {
                $('.loading-text').remove();
            }
        });
    }
}); 
});
4

1 回答 1

3

由于您的文本文件包含 html 标记,因此您可以使用 jQuery 进行操作。

success: function (data) {
    var people = $(data),
        john = people.filter('#John_Resig');

    $(".demo-cb-tweets").empty().append(john);
}

在 jQuery 对象中包装一串 html 会将其转换为 jQuery 对象,然后您可以使用该对象并将其插入到 dom 中,即:$('<div>Test</div>').addClass('test-class').appendTo('body');

编辑:提取名称:

您可以以相同的方式从文本文件中提取名称。例如,在页面加载时,如果您对将一直初始化的文本文件进行 ajax 调用。以下代码将获取您的文本文件,并遍历每个容器元素(在您的示例中,John_Resig 和 Tim_Berners_Lee):

success: function (data) {
    var people = $(data);

    people.each(function (i, person) {
        var name;
        if (person.nodeType !== 3) { // Your text file example had a blank line between the containing div elements... which loads as a nodeType of 3, so we'll want to skip those.
            name = $('.contact', person).text(); // This would grab the text inside of the div with the class 'contact'.
            // do stuff with that name here...

        }
    });
}
于 2012-12-20T13:12:06.950 回答