我如何把这个JavaScript变成jQuery

时间:2019-03-23 21:29:20

标签: javascript jquery html css

我正在对此W3Schools tutorial进行自定义。我想使用jQuery向选项卡之间的过渡添加动画。这是javascript函数中的相关行

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";

我已经尝试过了,但是没有用。

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  $("x[n]").show(750);
}

2 个答案:

答案 0 :(得分:2)

您当前正在尝试获取元素<x n="something">。只需删除引号,使其不是选择器而是jQuery对象:

function showTab(n) {
  var x = document.getElementsByClassName("tab");
  $(x[n]).show(750);
}

答案 1 :(得分:2)

您需要将x[n]的值提供给jQuery构造函数,而不是作为字符串文字:

$(x[n]).show(750);

话虽如此,如果您想将其完全转换为jQuery,则可以使用jQuery对象和eq()方法来通过索引检索其中的元素:

function showTab(n) {
  $('.tab').eq(n).show(750);
}