JSFIddle不使用Jquery

Tom*_*mas 1 javascript jquery jsfiddle

在研究这个问题的答案时,我创造了这个jsfiddle.由于某种原因,它不起作用,当我使用firebug的错误consol时它返回".show"不是一个函数.这让我相信jsfiddle错误地加载jQuery.JSFiddle和jQuery之间是否存在任何已知问题?我的代码是不正确的(BTW当我.show("slow")改为.style.display = "inherit"它工作正常,这就是为什么我认为它必须是jQuery的问题...)

一个工作的JSFiddle将不胜感激.

Bra*_*tie 6

几个问题:

  1. 你忘记了}.
  2. 您正在对未包装在jQuery对象中的元素调用jQuery方法.你需要这样做:

$(itemName.getElementsByTagName("span")[0]).show("slow");
Run Code Online (Sandbox Code Playgroud)

(注意包装).jQuery方法不会神奇地扩展默认元素,必须首先包装对象.

现在请注意,此版本有效.

编辑:

或者,您可以使用jQuery构造(范围)的第二个参数并缩短此代码:

function showy(itemName) {
    $('span:first',itemName).show("slow");
}
function closy(itemName) {
    $('span:first',itemName).hide("slow");
}
Run Code Online (Sandbox Code Playgroud)

EDITv2

胡安提出了一个很好的观点,你也应该将javascript与标记分开.我的意思是避免使用元素的on*属性,并将绑定保留在外部.js文件或<script>标记内.例如

<head>
  ...
  <script src="http://path.to/jquery.js">
  <script>
    $(function(){ // execute once the document is ready (onload="below_code()")

      // bind to the buttons' hover events
      // find them by the "button" and "white" class names
      $('.button.white').hover(function(){ // hover event (onmouseover="below_code()")

        // find the first span within the link that triggered the event
        $('span:first',this).show('slow');

      },function(){ // mouse out event (onmouseout="below_code()")

        // likewise, find first span
        $('span:first',this).hide('slow');

      });
    });
  </script>
  ...
</head>

<body>
  ...
  <a href="#" class="button white" id="button1">
    <span id="spanToShow">SHOW: this text&nbsp;</span>
    on hover
  </a>
  ...
</body>
Run Code Online (Sandbox Code Playgroud)