javascript - jQuery: Set Element Attributes Using Object Values and Subvalues -
i update weekly schedule using following static table:
<table> <tr class="live gm fsp"> <td>oct. 7</td> <td>12:30 pm</td> <td class="prog">show 1</td> <td>team v team b</td> <td class="tv-logo"></td> </tr> <tr class="gm dtv"> <td>oct. 7</td> <td>4 pm</td> <td class="prog">show 2</td> <td>team c v team d</td> <td class="tv-logo"></td> </tr> <tr class="usa gm pnc"> <td>oct. 7</td> <td>6 pm</td> <td class="prog">show 3</td> <td>team e v team f</td> <td class="tv-logo"></td> </tr> <tr class="gm pnc"> <td>oct. 7</td> <td>8 pm</td> <td class="prog">show 3</td> <td>team e v team f</td> <td class="tv-logo"></td> </tr> </table> the class attribute of <tr> element determine inner html of <td class="tv-logo"></td> child element. inner html supposed linked <img/> of student tv channel logo. image src , alt (which use title) attributes contained in following object:
var networkclass = { 'fsp' : { 'src' : '/images/page-items/fsp.png', 'alt' : 'first student productions' }, 'dtv' : { 'src' : '/images/page-items/dtv.png', 'alt' : 'digital travel vlog' }, 'pnc' : { 'src' : 'http://4.bp.blogspot.com/-i9u1bdkwzzk/ur3wrv2vdsi/aaaaaaaaajw/fqbp37byf5y/s100/bmw_logo_black_white.png', 'alt' : 'production new cinema' }, 'usa pnc' : { 'src' : 'http://www.qservice.ro/assets/images/brands/slider_16.png', 'alt' : 'production new cinema' } } the class usa sets corresponding <tr> have solid colored background requires white version of corresponding tv channel logo.
using answer found here (or http://jsfiddle.net/3wgmr/1/), can match class if has single value not 2 values. how set inner <img/> html of <td class="tv-logo"></td> while setting it's attributes using object? or advice appreciated!
if keys in networkclass valid css selectors use .is determine if element in question satisfies them, , in way reach result looking for.
the keys not selectors, if can assume whitespace-separated lists of css class names it's easy transform them selectors:
var key = "pnc usa"; var selector = key.replace(/(^|\s+)(\s+)/g, ".$2"); // ".pnc.usa" so can write this:
$('tr[class]').each(function() { var $tr = $(this); $.each(networkclass, function(key, attributes) { var selector = key.replace(/(^|\s+)(\s+)/g, ".$2"); if ($tr.is(selector)) { $tr.children(".tv-logo").append($("<img>", attributes)); break; } }); }); however, have pay attention details here: since .foo strictly less-specific selector .foo.bar , selector matches first determine result, must take care more specific selectors appear before less-specific ones on networkclass object:
var networkclass = { // 'pnc usa' : { 'src' : '/images/page-items/pnc-white.png', 'alt' : 'production new cinema' } // must appear before 'pnc' : { 'src' : '/images/page-items/pnc.png', 'alt' : 'production new cinema' }, }
Comments
Post a Comment