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);
}

html の文字列を jQuery オブジェクトでラップすると、それが 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 に答える