【问题标题】:jQuery - Replace div class when click a listjQuery - 单击列表时替换 div 类
【发布时间】:2013-06-12 13:59:09
【问题描述】:

有人可以帮我编写一个 jQuery 脚本,以便在单击链接时将 div 类替换为另一个类。 我有一个地址列表,我希望在单击地址时更改地图图像。由于图像上的 css 和渐变结构,简单地更改背景图像 url 无济于事。 我为每个地址创建了 4 个类,每个类都有每个地址的背景图像。

我已经简化了我的代码,以便更容易编写脚本。这是我构建的:

图像包装器:

<div class="map-wrapper map1">
</div>

地址列表:

<ul>
    <li><a href="#map1">Address 1</a></li>
    <li><a href="#map2">Address 2</a></li>
    <li><a href="#map3">Address 4</a></li>
    <li><a href="#map4">Address 5</a></li>
</ul>

我之前使用的 jQuery,当时我只是在 map-grad 标记中更改了一个。

 var itemInfo = { // Initialise the item information
      img1: ['/img/map.png', ''],
      img2: ['/img/ealing_map.jpg', ''],
};

$(function() {
      $('#maps a').click(function() { // When an item is selected
            var id = $(this).attr('href').replace(/#/, ''); // Retrieve its ID
            $('#info img').attr('src', itemInfo[id][0]); // Set the image
            $('#info p').text(itemInfo[id][1]); // And text
            return false; // Prevent default behaviour
      });
});

我想编写一个 jQuery 脚本,在单击相关地址链接时将类“map1”更改为“map2、3 或 4”。这反过来会改变背景图像! :)

那么,谁能帮帮我!我是 javascript 和 jQuery 新手,知道的不多!

【问题讨论】:

  • 什么是#maps&lt;ul&gt;?

标签: javascript jquery html image replace


【解决方案1】:
$('ul li a').on('click', function(e) {
    e.preventDefault();
    var cl = $(this).attr('href').replace('#','');
    $('.map-wrapper').removeClass().addClass('map-wrapper '+cl);
});

FIDDLE

【讨论】:

  • @LightStyle - 我自己也注意到了,我猜打字速度很快,谢谢!
  • 有时会发生,别担心:D +1!
【解决方案2】:

你需要类似的东西

$('.map-wrapper').removeClass().addClass('map-wrapper '+$(this).attr('id'));

【讨论】:

    【解决方案3】:

    在你的函数末尾添加以下内容:

    $(".map-wrapper").removeClass("map1 map2 map3 map4").addClass(id);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-29
      • 2017-07-23
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多