简体   繁体   中英

How can I make this code more effective using Javascript or jQuery?

I want to create 10 in-body links by <a> tag of course. In the demo you can see that the code is too long for only 3 links and I'm sure that there's a way to improve this code.

So, how can I know which link was selected and what can I do with this information?

function fillYellow() {
    var paintedDiv = document.getElementsByClassName('painted')[0];
    paintedDiv.style.background = "yellow";
    setTimeout(function () {
        if (paintedDiv.style.background == "yellow") {
            paintedDiv.style.background = "#e5e5e5";
        }
    }, 3000);
}

function fillYellow1() {
    var paintedDiv = document.getElementsByClassName('painted')[1];
    paintedDiv.style.background = "yellow";
    setTimeout(function () {
        if (paintedDiv.style.background == "yellow") {
            paintedDiv.style.background = "#e5e5e5";
        }
    }, 3000);
}

function fillYellow2() {
    var paintedDiv = document.getElementsByClassName('painted')[2];
    paintedDiv.style.background = "yellow";
    setTimeout(function () {
        if (paintedDiv.style.background == "yellow") {
            paintedDiv.style.background = "#e5e5e5";
        }
    }, 3000);
}

DEMO: http://jsbin.com/panarupo/1/edit

I'll use a jQuery event handlers with a data-* attribute like

<ul>
    <li><a href="#" class="fillYellow" data-target=".yellow">Using our site</a></li>
    <li><a href="#" class="fillYellow" data-target=".yellow1">NonUsing our site</a></li>
    <li><a href="#" class="fillYellow" data-target=".yellow2">Blablba our site</a></li>
</ul>
<h2 class="painted yellow">Using our site</h2>
<h2 class="painted yellow1">NonUsing our site</h2>
<h2 class="painted yellow2">BLAbla our site</h2>

then

jQuery(function ($) {
    $('.fillYellow').click(function () {
        var $target = $($(this).data('target')).css('background', 'yellow');
        setTimeout(function () {
            $target.css('background', '#e5e5e5');
        }, 3000);
    })
})

Demo: Fiddle

  • Add the class fillYellow to all trigger elements
  • Add a data-target attribute to the trigger elements with a selector value targeting the element that has to be highlighted
  • Add separate classes like yellow , yellow1 ,... etc to the target elements

Give common class for all the links. Then you can use like

$(".className").click(function(){ alert($(this).attr("href")); });

You dont have to give inline call for each anchor tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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