+ Reply to Thread
Results 1 to 2 of 2

Thread: Nesting HTML tags using JQuery

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    28

    Nesting HTML tags using JQuery

    I want to have a list of links that trigger another Javascript function when clicked.
    The code I have right now makes the <li> tags successfully,
    but the inner JQuery is returning an object ("1. [object Object]") instead of the text with a link tag wrapped around it.
    Code:
    $('<li></li>', {
        text: $('<a></a>', {
            text: data[i].name,
            onclick: 'doSomething()'
        }),
        id: 'response'
    }).appendTo('ol.responseList');

  2. #2
    Junior Member
    Join Date
    Apr 2012
    Posts
    34
    Use html instead of text.
    Code:
    $('<li></li>', {
        html: $('<a></a>', {
            text: data[i].name,
            onclick: 'doSomething()'
        }),
        id: 'response'
    }).appendTo('ol.responseList');
    P.S. I suggest not using onclick attributes to bind events. Use jQuery's event API.
    Code:
    $('<li></li>', {
        html: $('<a></a>', {
            text: data[i].name
        }).click(doSomething),
        id: 'response'
    }).appendTo('ol.responseList');
    UPDATE: If you want to pass i to doSomething, you need to do something like this (outside of the loop):
    Code:
    function createFunc(i){
        return function(){
            doSomething(i);  // this will be the correct value of `i`
        };
    }
    And then do this:
    Code:
    $('<li></li>', {
        html: $('<a></a>', {
            text: data[i].name
        }).click(createFunc(i)),  // Yes, this should be `createFunc(i)`, it returns a function
        id: 'response'
    }).appendTo('ol.responseList');

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts