Rad
Rad

Reputation: 830

Getting li-value from click and into onClick-method

I have these three li's, which shows perfectly on screen using this addToListview-method. When I click one of these, it runs the "test()"-method, which is also good. But I need the "tempobj.name" (or the shown on-screen name) of the clicked field as a parameter, as in test(TextOnTheChosenLi);, since I need it to get the right "obj.page". How do I do that?

  function addToListview(){
var listofitems = [];


var item1 = new Object;
var item2 = new Object;
var item3 = new Object;
item1.name = "item1"
item1.page = "info1"
item2.name = "item2"
item2.page = "info2"
item3.name = "item3"
item3.page = "info3"

listofitems.push(item1);
listofitems.push(item2);
listofitems.push(item3);

for (var i=0; i<listofitems.length; i++)
{
tempobj = listofitems[i];

$('ul').append($('<li/>', {    
'data-role': "list-divider"
}).append($('<a/>', {    
    'href': 'somepage.html',
    'onclick': 'test()',
    'data-transition': 'slide',
    'text': tempobj.name

})));


    }
$('ul').listview('refresh');
}

Upvotes: 1

Views: 636

Answers (2)

Emil A.
Emil A.

Reputation: 3445

You can make the code a little cleaner:

var list = [
    {
        name: "item1";
        page: "info1"
    },
    {
        name: "item2";
        page: "info2"
    },
    {
        name: "item3";
        page: "info3"
    }
];


function addToListview(arr, dest){

    var list = "";

    for (var i = 0, ilen = arr.length; ilen; i += 1) {
        list += '<li>' + 
                    '<a href="somepage.html" data-transition="slide">' + 
                        arr[i].name + 
                    '</a>' +
                '</li>';
    }


    $(dest).append(list);
    // unbind so you won't bind multiple events if the function is 
    // executed more than once
    $(dest + " > a").unbind().on('click', function (e) {
        e.preventDefault();
        test(this);
    });

};

addToListview(list, '#destination');

Upvotes: 0

PherricOxide
PherricOxide

Reputation: 15919

This probably isn't the best solution using jquery, but I think it does what you're looking for at least: http://jsfiddle.net/LvE7e/

function test(obj) {
    alert(obj.text);   
}


...

'onclick': 'test(this)',

...

Upvotes: 1

Related Questions