0

我试图让这些 jQuery 命令稍后通过 html 中的链接执行:

                    $('#mov').click(function() {
                            $('#twastream').hide();
                            $('#ownstream').hide();                                     
                            $('#movstream').fadeIn();
                    }

这应该隐藏两个元素并在单击 id 为“mov”的链接后显示一个,但没有发生任何事情。这是链接:

                    <a href="test/#" onclick="mov()">Click here!</a>

这是元素;这三个都具有类似的格式。

                   <div class="movstream" id="movstream">

我应该如何更改这些格式以使初始代码正确运行?

4

4 回答 4

3

You need to have an id on your anchor tag for your jquery selector $('#mov') to work:

<a href="test/#" id="mov">Click here!</a>

Using onclick="mov()" on your anchor means to execute a function named mov, which is undefined

You also need to wrap your .click event in $(document).ready():

$(document).ready(function(){
    $('#mov').click(function() {
        $('#twastream').hide();
        $('#ownstream').hide();                                     
        $('#movstream').fadeIn();
    }
});

Otherwise the element may not exist when the script runs

于 2012-12-21T22:14:25.867 回答
0

The strength of jQuery is in its ability to make tasks like this mundane.

First, give your link either a class or an id (a class would work if this can happen on any given number of links) and then bind your event in the background, like this:

HTML

<a href="/#" class="test" /> 
<!--OR-->
<a href="/#" id="test" /> 

JavaScript

$(".test").click(function(){ //Or $("#test")
     $('#twastream').hide();
     $('#ownstream').hide();                                     
     $('#movstream').fadeIn();
});

It might be helpful to go and review the jQuery API, too.

于 2012-12-21T22:14:52.460 回答
0

Nothing is happening because you don't have an ID specified on the anchor. The jQuery is looking for a click on an element with the id of "mov" but there isn't an element with that id.

于 2012-12-21T22:16:19.027 回答
0

您应该在准备好的处理程序中侦听您的事件:

$(function() {
   $('#mov').click(function() {
      $('#twastream').hide();
      $('#ownstream').hide();                                     
      $('#movstream').fadeIn();
   });
}); 

http://api.jquery.com/ready/

而且您需要确保该.click函数正确指定了选择器。请注意,这是带有of$('#mov')的项目的选择器。这也适用于类。idmov

<a id="mov">Click here!</a>     
<div class="twastream" id="twastream">Twas</div>
<div class="ownstream" id="ownstream">Own</div>
<div class="movstream" id="movstream">Mov</div>

http://api.jquery.com/category/selectors/

于 2012-12-21T22:35:55.273 回答