正在更改<a> tag border-top&#39;s color in menu using jQuery FOR loop

时间:2015-09-25 16:36:04

标签: javascript jquery css

I want to add to my menu a colorful border-top. I know that I can do that with only HTML (by adding style="border-top-color: red;"), but I'm just curious to know how to do this using jQuery.
This is what I've tried so far:

var colors = ['purple', 'yellow', 'orange', 'black'];
for(int i=0; i<4; i++){
    $("li").html("<a style= 'border-top-color: colors[i]'>");

I've tried also replacing the $("li") with $("a") but it doesn't work.

Any suggestions? Thank you!

3 个答案:

答案 0 :(得分:3)

我认为你真正想要的是:

&#13;
&#13;
var colors = ['purple', 'yellow', 'orange', 'black'];
$("li a") //select all the anchors
  .each(function(index) { //loop through anchors
    var current = $(this); //current anchor being looped over
    current.css("border-top-color", colors[index]); //set the border top color based on the index
  });
&#13;
ul li {
    display: inline;  
    text-decoration: none;
}

li a { 
    display: inline-block;
    border-top: 5px solid transparent;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Link 1</a></li>
  <li><a href="#">Link 2</a></li>
  <li><a href="#">Link 3</a></li>
  <li><a href="#">Link 4</a></li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

TRY

var colors = ['purple', 'yellow', 'orange', 'black'];
for(int i=0; i<4; i++){
    $("li").append("<a style= 'border-top-color: "+colors[i]+"'>");
  1. .html会覆盖你里面的内容 真正的问题是你为什么要这样做?

答案 2 :(得分:0)

如果没有看到HTML的结构,那就很难了。但是类似的东西:

 number_of_cmd_files = cmd_files.length;
 update_log('Running CMDs')
 i=0;
 cmd= cmd_files[i];

 wait_for_cmd_complete(cmd)

 function wait_for_cmd_complete(cmd){

    update_log("Waiting for CMD " + cmd + " to complete...")

   $.ajax({
        type: 'POST',
        data: {cmd:cmd}, 
        url: 'wait_for_cmd_complete.php'

    }).done(
         function(value) {
         i++;  
         update_log( "    CMD complete for: " + cmd);
         if (i < number_of_cmd_files) {
           cmd = cmd_files[i]
           wait_for_cmd_complete(cmd);  
         }
       }
    ); 

应该是一个好的开始。