jQuery如何使用变量和字符串使此更简单



我如何使用变量和字符串使此更简单

      $('#department_categories h4:contains("Kitchen")').parent().css('background-image', 'url("some-image.jpg');
      $('#department_categories h4:contains("Bathroom")').parent().css('background-image', 'url("some-image.jpg');
      $('#department_categories h4:contains("Decorating")').parent().css('background-image', 'url("some-image.jpg');
      $('#department_categories h4:contains("DIY")').parent().css('background-image', 'url("some-image.jpg');
      $('#department_categories h4:contains("Garden")').parent().css('background-image', 'url("some-image.jpg');
      $('#department_categories h4:contains("Homeware")').parent().css('background-image', 'url("some-image.jpg');
      $('#department_categories h4:contains("Lighting")').parent().css('background-image', 'url("some-image.jpg');
      $('#department_categories h4:contains("Christmas")').parent().css('background-image', 'url("some-image.jpg');
var homeObjects = ["Kitchen", "Bathroom", "Decorating","DIY","Garden","Homeware","Lighting","Christmas"];
var i;
for(i=0;i<homeObjects.length;i++)
{
    $('#department_categories h4:contains('+homeObjects[i]+'])').parent().css('background-image', 'url("some-image.jpg');
}

假设您每页只使用一次,则可以确保文件名与<h4/>文本相关:

var backgroundImage = '/path/to/image/' + $('#department_categories h4').text() + '.jpg';
$('#department_categories h4').parent().css('background-image', 'url("' + backgroundImage + '")');

但是,如果您想要在不同父容器中通过几个不同的<h4/>循环,则可以运行每个循环:

$('#department_categories h4').each(function() {
    var backgroundImage = '/path/to/image/' + $(this).text() + '.jpg';
    $(this).parent().css('background-image', 'url("' + backgroundImage + '")');
});

如果您的某些标题有空格或特殊字符,我建议使用正则

var backgroundImage = '/path/to/image/' + $('#department_categories h4').text().replace(/W+/g, '-') + '.jpg';
$('#department_categories h4').parent().css('background-image', 'url("' + backgroundImage + '")');

$('#department_categories h4').each(function() {
    var backgroundImage = '/path/to/image/' + $(this).text().replace(/W+/g, '-') + '.jpg';
    $(this).parent().css('background-image', 'url("' + backgroundImage + '")');
});

个人,如果您要在多个<h4/>父容器上进行此操作,我会降低文本:

$('#department_categories h4').each(function() {
    var backgroundImage = '/path/to/image/' + $(this).text().replace(/W+/g, '-').toLowerCase() + '.jpg';
    $(this).parent().css('background-image', 'url("' + backgroundImage + '")');
});

codepen demo

相关内容

最新更新