简体   繁体   English

不引人注目的JavaScript

[英]Unobtrusive JavaScript

I'm tyring to learn JavaScript and i'm following some tutorials to learn it. 我正在学习JavaScript,我正在学习一些教程。 In one is some simple code to teach about Unobtrusive JavaScript code. 其中一个是教授Unobtrusive JavaScript代码的简单代码。 The code is simple, it needs to show a message when JavaScript is not active and when it is active it needs to show a plus sign that is clickable. 代码很简单,它需要在JavaScript未激活时显示消息,当它处于活动状态时,它需要显示可点击的加号。

Below the html code: 在html代码下面:

 <body>
     <h1 id="title">18. Unobtrusive JavaScript</h1>
     <p id="main">

     </p>
     <p id="message">You should see this whether JavaScript is on or off.</p>
 </body>

And the JavaScript/jQuery code: 和JavaScript / jQuery代码:

$(function() {
    $('#main').append("<img src='plus-8.png' alt='Click me to see the paragraph'    id='clickMe' />");

$('#clickMe').toggle(function() {
    $('#message').show('fast');
    $('#clickMe').attr('src', 'minus-8.png');

}, function() {
    $('#message').hide('slow');
    $('#clickMe').attr('src', 'plus-8.png');
});

$('#message').hide();

});

I only see the plus sign appear shortly and then it disappears. 我只看到加号很快出现,然后就消失了。 When I look at the source code the #main is there but has a display: none; 当我查看源代码时,#main就在那里但是有一个display:none; and the #message also doesn't show. 并且#message也没有显示。 I can't get it to work and can't find out what I'm doing wrong. 我无法让它工作,也无法找出我做错了什么。 If somebody could help me, that would be nice. 如果有人可以帮助我,那就太好了。

jQuery toggle method can take three parameters, first is duration, second is easing (fast, slow) and third is function callback when animation is complete. jQuery toggle方法可以采用三个参数,第一个是持续时间,第二个是缓动(快速,慢速),第三个是动画完成时的函数回调。 You are passing two functions in toggle method, and hence when it completes showing your message, it then hides it in the second function call back. 您在toggle方法中传递了两个函数,因此当它完成显示您的消息时,它会在第二个函数回调中隐藏它。

Do something like this: 做这样的事情:

$('#clickMe').click(function() {
    $('#message').toggle('slow');

    // If image is plus, display minus
    // If image is minus, display plus
    if($('#clickMe').attr('src') === 'plus.svg') {
        $( '#clickMe').attr('src', 'minus.svg');
    } else {
        $( '#clickMe').attr('src', 'plus.svg');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM