2014-03-03 37 views
0

我想通過<a>標籤創建10個正文鏈接。在演示中,您可以看到只有3個鏈接的代碼太長,我相信有一種方法可以改進此代碼。如何使用Javascript或jQuery使此代碼更有效?

那麼,我怎麼知道哪個鏈接被選中,我該怎麼處理這些信息呢?

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

+2

您想更高效嗎?使用合理的縮進! – Bergi

+0

懶人們有一個工具:http://jsbeautifier.org/。 – leaf

+0

我自己做的... – leaf

回答

1

我會用一個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); 
    }) 
}) 

演示:Fiddle

  • fillYellow添加到所有觸發元素
  • 添加data-target屬性與一個選擇器的值的觸發元件靶向具有被加亮
  • 添加單獨的類似yellowyellow1,...等的元件到目標元素
0

給普通類的所有環節。然後你就可以像使用

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

你不必給內聯呼籲每個錨標記

+1

OP不使用jQuery。 –

+0

@ mori57。他用jquery標記了他的問題。那就是爲什麼.. –

+0

+1,這個問題包含'jQuery'標籤。 :-) –