有没有办法将此jquery代码转换为javascript?

时间:2011-08-08 00:38:53

标签: javascript jquery

我正在尝试创建标签菜单。我需要在常规javascript中编码,而不是jquery。

$(document).ready(function() {
//When page loads...
$(".general_info_content").hide(); //Hide all content
$("ul.general_info_tabs li:first").addClass("active").show(); //Activate first tab
$(".general_info_content:first").show(); //Show first tab content

//On Click Event
$("ul.general_info_tabs li").click(function() {

    $("ul.general_info_tabs li").removeClass("active"); //Remove any "active" class
    $(this).addClass("active"); //Add "active" class to selected tab
    $(".general_info_content").hide(); //Hide all tab content

    var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
    $(activeTab).fadeIn(); //Fade in the active ID content
    return false;
});
});

2 个答案:

答案 0 :(得分:1)

您想要做的核心是 - 我确信每种任务都有一千种不同的方式:

从元素中删除CSS类:

var classes = document.getElementById([id]).className.split(" ");
for(var i = 0; i < classes.length; i++)
    if(classes[i] == removeClass) 
          classes[i] = "";
document.getElementById([id]).className = classes.join(" ");

为元素添加CSS类:

document.getElementById([i]).className += " " + addClassName;

隐藏元素:

document.getElementById([i]).style.display = "none";

淡化元素:

// not tested, but based on tested/used code
function fade(el, opacity, fadeInTime) {
     if (opacity < 100) {
          el.style.opacity = opacity / 100;
          el.style.filter = "alpha(opacity=" + opacity + ")";
          opacity += 5;

          setTimeout(function () { fade(el, opacity, fadeInTime); }, fadeInTime / 5);
     }
}

按CSS和标签名称查找所有元素:

var matches = new Array();
var all = document.getElementByTagName(searchTagName);
for(var i = 0; i < all.length; i++){
     if(all[i].className.replace(searchClassName, "") != all[i].className) {
           matches.push(all[i].className);
     }
}
// do something with (i.e., return or process) matches

为了记录,我发现使用jQuery库的人想要知道如何使用原生JS / DOM完成任务是令人鼓舞的,而不是无理的。

答案 1 :(得分:1)

更多功能可以补充Brian的帖子。祝好运。

编辑:正如我所提到的,我会将class = general_info_content更改为id = general_info_content1。

  function attach(el, event, fnc) {
      //attach event to the element
      if (el.addEventListener) {
          el.addEventListener(event, fnc, false);
      }
      else if (document.attachEvent) {
          el["on" + event] = fnc;  // Don not use attachEvent as it breaks 'this'
      }
  }

  function ready() {
    // put all your code within $(function(){}); here.
  }

  function init() {
      attach(document, "readystatechange", function () {
          if (document.readyState == "complete") {
              ready();
          }
      });
  }