簡體   English   中英

如何使用Javascript或jQuery使此代碼更有效?

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

我想通過<a>標簽創建10個體內鏈接。 在演示中,您可以看到該代碼對於3個鏈接來說太長了,我敢肯定有一種方法可以改進此代碼。

因此,我如何知道選擇了哪個鏈接以及如何處理此信息?

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);
}

演示: http : //jsbin.com/panarupo/1/edit

我將使用具有data- *屬性的jQuery事件處理程序,例如

<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>

然后

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

演示: 小提琴

  • 將類fillYellow添加到所有觸發器元素
  • data-target屬性添加到觸發器元素,並使用選擇器值作為必須突出顯示的元素
  • 向目標元素添加單獨的類,例如yellowyellow1 ,...等

為所有鏈接提供通用類。 然后你可以使用像

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

您不必為每個錨定標簽進行內聯調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM