简体   繁体   中英

jQuery Listview changing list item color

I suck so hard at javascript - I can't figure out how to change the background color of a list item in a jquery listview...

var parent = document.getElementById('listDiv');

var listview = document.createElement('ul');
listview.setAttribute('id', 'listView');

parent.appendChild(listview);
var listItem = document.createElement('li');
listItem.setAttribute('id', 'temp');
var itemLink = document.createElement('a');
itemLink.setAttribute('href', '#');
itemLink.innerHTML = "HEYY MAN";

listItem.appendChild(itemLink);
listview.appendChild(listItem);


$('#listView').listview().listview('refresh');

//I NEED DIS SHIT TO WORK
$('#listView').on('click', 'li', function(){
    $('#temp').css('background-color','green');   
});

Everything is displayed correctly, and you can play around with it on JSFiddle , but either the 'click' functionality or the background color change is not working correctly. Can someone lend a helping hand?

The version of jQuery you're using (1.6.4) doesn't support the .on() function, it was only introduced in version 1.7. I've replaced it with .bind() to get it working temporarily:

$('#listView').bind('click', 'li', function(){
    $('#temp').css('background','green');   
});

background-color was changed to just background in order to override the jQuery Mobile styling.

Here it is working: http://jsfiddle.net/q3vfh/3/

However, if you're not tied to that version of jQuery then I'd recommend using the code from this updated fiddle: http://jsfiddle.net/q3vfh/2/ - it uses jQuery 2.0.2 and jQuery Mobile 1.3.1 and allows you to use .on() .

$('#listView').delegate('li','click', function(){
$(this).css({background: '#6495ED'})   
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM