开发者

JQuery quiz app - highlight unordered list entry and call function

I'm creating a quiz app with JQuery, JQtouch & Phonegap. The main screen shows a question in one unordered list, then 5 possible answers in the second list. The info is pulled from an sqlite db and the page dynamically created.

I want the user to be able to click on a row in the answer ul, which will then highlight that row, unhighlight any other entries in the unordered (answer) list and call a function. I've looked through reams of example code, but can't get my head around the implementation. My page contains a div:

<div id="answer_template2"></div>

which is filled by the database query & dynamically built page:

    var questionHTML = "<ul class=\"rounded\" id="question">";
    var answerHTML = "<ul class=\"rounded\" id="answers">";

    for (var i=0; i<results.rows.length; i++)
    { 
        var row = results.rows.item(i); 
        questionHTML += '<li>'+row['question_text']+'</li>\n';
        answerHTML += '<li>'+row['answer1_text']+'</li>\n';
        answerHTML += '<li>'+row['answer2_text']+'</li>\n';
        answerHTML += '<li>'+row['answer3_text']+'</li>\n';
        answerHTML += '<li>'+row['answer4_text']+'</li>\n';
        answerHTML += '<li>'+row['answer5_text']+'</li>\n';

    questionHTML +='</ul>';
    answerHTML +='</ul>';

    //alert(questionHTML);

    // ouput database result into question_template id section of page
    document.getElementById('question_template2').innerHTML = questionHTML;
    document.getElementById('answer_template2').innerHTML = answerHTML;

I've also got a function:

    $("li").click(function() 
{
    alert("yes");
});

which pops up the alert when a static li eleme开发者_C百科nt is clicked but not when any of my dynamically created list elements are selected but can't figure out how to put it all together. Any help would be gratefully received! Thanks, Nick.


First of all, jQuery events are only bound to elements it finds when you execute the selector.

There are two common ways of getting around this:

  1. Use .live() or .delegate() to bind your events to the document (or some other container) and have them check for a target that is within an LI.

    $("li").live('click', function() { alert("hi"); });
    
  2. Re-bind your handlers to the newly created content:

    // ouput database result into question_template id section of page
    document.getElementById('question_template2').innerHTML = questionHTML;
    document.getElementById('answer_template2').innerHTML = answerHTML;
    $("#answer_template2 li, #question_template2 li").click( handler );
    

Also, just as a side note - $("#question_template2").html(questionHTML); is a little safer to use rather than injecting your HTML directly to innerHTML. It will give jQuery a chance to unbind/cleanup the memory for the elements you are removing by destroying innerHTML.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜