jQuery/Javascript(从ID转换为Class) [英] Jquery/Javascript ( Convert from ID to Class )

查看:82
本文介绍了jQuery/Javascript(从ID转换为Class)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了这个脚本.但是现在我需要将这些id转换为类,因为我应该将其放在页面的其他元素中.

I did this script. But now i need to convert these id to classes because should I put it in other elements of the page.

 var init = function() {
      var card = document.getElementById('card');
      
      document.getElementById('flip').addEventListener( 'click', function(){
        card.toggleClassName('flipped');
      }, false);
    };
    
    window.addEventListener('DOMContentLoaded', init, false);

你能帮我吗?

解决方案:

$(function() {
  var card = $('.card');
  
  $('.flip').on( "click", function(){
    card.toggleClass('flipped');
    return false;
  });
});

推荐答案

由于您已标记了,我可以这样:

Since you have tagged with jquery, I would give this:

// Once document is loaded,
$(function () {
  // Change all the `#card`, `#flip` to classes:
  $("#card, #flip").addClass(function () { return this.id; }).removeAttr("id");
});

首先,它选择所有#card#flip,应该只有2个元素.它将它们各自的id添加为class,并删除id属性.

First it selects all the #card and #flip, there should be only 2 elements. It adds their respective id as class and removes the id attribute.

代码段

// Once document is loaded,
$(function () {
  // Change all the `#card`, `#flip` to classes:
  $("#card, #flip").addClass(function () { return this.id; }).removeAttr("id");
});

.card {background: #f99;}
.flip {background: #9f9;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="card">Card</div>
<div id="flip">Flip</div>

如果您只想添加额外的类,则可以使用以下内容:

If you just wanna add the extra classes, then you can use this:

$(function() {
  var card = $('.card');

  $('.flip').on( "click", function(){
    card.toggleClass('flipped');
    return false;
  });
});

这篇关于jQuery/Javascript(从ID转换为Class)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆