使用ajax从文本文件中的特定div加载文本
我正在使用jquery hovercard插件在用户将鼠标hover在特定文本字符串上时使用ajax从文本文件中提取文本 – 这一切都很有用 ,(下面的代码)。
现在我想要做的是在文本文件中有许多不同的div(如下所示),并根据hover在哪个文本字符串上拉相关的div。 这可能与Jquery / Ajax有关,如果是的话,你怎么做呢?
//文本文件内容
John Resig Testing testing testing!
And on another line of text : )
Tim Berners-Lee Testing testing testing!
And on another line of text : )
// Jquery / Ajax代码
$(document).ready(function () { var hoverHTMLDemoAjax = ''; $(".demo-ajax").hovercard({ detailsHTML: hoverHTMLDemoAjax, width: 350, delay: 500, cardImgSrc: 'http://sofzh.miximages.com/jquery/short.sm.jpg', onHoverIn: function () { $.ajax({ url : "helloworld.txt", type: 'GET', dataType: "text", beforeSend: function () { $(".demo-cb-tweets").prepend('Loading latest tweets...
'); }, success: function (data) { $(".demo-cb-tweets").empty(); $(".demo-cb-tweets").html(data); }, complete: function () { $('.loading-text').remove(); } }); } }); });
由于您的文本文件包含html标记,因此您可以使用jQuery进行操作。
success: function (data) { var people = $(data), john = people.filter('#John_Resig'); $(".demo-cb-tweets").empty().append(john); }
在jQuery对象中包装一串html会将其转换为jQuery对象,然后您可以使用它并插入到dom中,即: $('
Test
').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... } }); }