我想将动态标题附加到<a> tag which is static for now

时间:2018-04-04 09:03:22

标签: javascript jquery

<ol class="flex-control-nav flex-control-paging">
 <li>
     <a href="#" title="#IR201800" class="flex-active">1</a>
 </li>
 <li>
     <a href="#" title="#IR201800">2</a>
 </li>
 <li>
      <a href="#" title="#IR201800">3</a>
 </li>
</ol>

Currently the title="#IR201800". It's static and I want to append the title dynamically.

I've tried this code:

function appendTitles() {
  $(".slides").find(".flex-control-paging li").each(function() {
    var atag = $(this).parents('li').find('a');
    atag.attr("title", "Raaj");
  })
}

3 个答案:

答案 0 :(得分:1)

使用attr像这样循环和分配值。

&#13;
&#13;
var title = ['a', 'b', 'c']; // Your dynamic content List
$('ol > li').find('a').each(function(index, element) {
  $(this).attr('title', title[index])
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ol class="flex-control-nav flex-control-paging">
  <li>
    <a href="#" title="#IR201800" class="flex-active">1</a>
  </li>
  <li>
    <a href="#" title="#IR201800">2</a>
  </li>
  <li>
    <a href="#" title="#IR201800">3</a>
  </li>
</ol>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

function appendTitles() {
        $(".slides").find(".flex-control-paging li").each(function(){
            var atag = $(this).find('a');
            atag.attr("title", "Raaj");
        })
}

试试这个。

。不需要parent()

请检查小提琴 here

答案 2 :(得分:0)

我希望你能找到这个解决方案:

&#13;
&#13;
function appendTitles() {
        $(".slides").find(".flex-control-paging li").each(function(){
            var atag = $(this).parent().find('a');
            atag.attr("title", "Raaj");
        })
}

appendTitles();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='slides'>
<ol class="flex-control-nav flex-control-paging">
 <li>
     <a href="#" title="#IR201800" class="flex-active">1</a>
 </li>
 <li>
     <a href="#" title="#IR201800">2</a>
 </li>
 <li>
      <a href="#" title="#IR201800">3</a>
 </li>
</ol>
</div>
&#13;
&#13;
&#13;

这是输出:

<li>
 <a href="#" title="Raaj" class="flex-active">1</a>
</li>