jQuery / Javascript在body标签

时间:2017-06-20 06:06:05

标签: javascript jquery html

我的HTML结构中有一堆带有不同ID的跨度,我希望通过每个跨度ID来切换正文标记上的类。 例如,如果我点击带有 ID_0 的跨度,我想在正文标签上切换类 ID_0 如果我点击 ID_1 ,请删除其他的并添加我点击的



$(".images").click(function(){
      var ids = $(this).attr("id");
      $("body").removeClass("ID_0 ID_1 ID_2 ID_3").addClass(ids);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
  <div class="Container">
    <span class="images" id="ID_0">ID_0</span>
    <span class="images" id="ID_1">ID_1</span>
    <span class="images" id="ID_2">ID_2</span>
    <span class="images" id="ID_3">ID_3</span>
  </div>
</body>
</html>
&#13;
&#13;
&#13;

使用php自动生成跨度,每个跨度都有自己的ID,可能有+15跨度,所以我很确定你可以做得比我的新手jquery编码好:)

3 个答案:

答案 0 :(得分:3)

以下代码将移除以ID_开头的所有类,因为这是您的“通配符”

$("body").removeClass(function(index, className) {
    return (className.match(/(^|\s)ID_\S+/g) || []).join(' ');
});

$(".images").click(function() {
  var ids = $(this).attr("id");
  $("body").removeClass(function(index, className) {
    return (className.match(/(^|\s)ID_\S+/g) || []).join(' ');
  });
  $("body").addClass(ids);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  <div class="Container">
    <span class="images" id="ID_0">ID_0</span>
    <span class="images" id="ID_1">ID_1</span>
    <span class="images" id="ID_2">ID_2</span>
    <span class="images" id="ID_3">ID_3</span>
  </div>
</body>

</html>

答案 1 :(得分:1)

据我了解,你想每次覆盖身体的类,是吗?我认为使用vanilla JavaScript最方便。请参阅下面的代码段。

$(".images").click(function(){
      var ids = $(this).attr("id");
      document.body.classList = ''; // Empty class list
      document.body.classList += ids; // Could merge the two statements into document.body.classList = ids;
      console.log(document.body.classList); // debugging
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
  <div class="Container">
    <span class="images" id="ID_0">ID_0</span>
    <span class="images" id="ID_1">ID_1</span>
    <span class="images" id="ID_2">ID_2</span>
    <span class="images" id="ID_3">ID_3</span>
  </div>
</body>
</html>

答案 2 :(得分:0)

你可以试试这个

&#13;
&#13;
$(".images").click(function(){
      var ids = $(this).attr("id");
      $("body").attr("class","").addClass(ids);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
  <div class="Container">
    <span class="images" id="ID_0">ID_0</span>
    <span class="images" id="ID_1">ID_1</span>
    <span class="images" id="ID_2">ID_2</span>
    <span class="images" id="ID_3">ID_3</span>
  </div>
</body>
</html>
&#13;
&#13;
&#13;