使用Jquery为ID,href和aria-controls添加动态值

时间:2017-11-14 10:20:40

标签: javascript jquery css twitter-bootstrap

我想为属性(href,id,aria-controls)添加动态值,这样我就可以在一个页面的多个位置切换文本。仅供您参考,我在提供的示例代码中的三个位置添加了“href =”#0_read_more“,aria-controls =”0_read_more“,id =”0_read_more“。同样,我增加了其他两个div部分的值,如在示例html代码中给出。请帮助我解决这个问题..

提前致谢。

<div class="image-text">
 <a href="#0_read_more" data-toggle="collapse" aria-expanded="false" aria-controls="0_read_more" class="collapsed">
                  Read More</a>
 <div id="0_read_more" class="collapse" aria-expanded="false" style="height: 0px;"><div>
</div>

<div class="image-text">
 <a href="#1_read_more" data-toggle="collapse" aria-expanded="false" aria-controls="1_read_more" class="collapsed">
                  Read More</a>
 <div id="1_read_more" class="collapse" aria-expanded="false" style="height: 0px;"><div>
</div>

<div class="image-text">
 <a href="#2_read_more" data-toggle="collapse" aria-expanded="false" aria-controls="2_read_more" class="collapsed">
                  Read More</a>
 <div id="2_read_more" class="collapse" aria-expanded="false" style="height: 0px;"><div>
</div>

3 个答案:

答案 0 :(得分:2)

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
for(i=0;i<3;i++)
{$("#mydiv").append("<div class='image-text'><a href='#"+i+"_read_more' data-toggle='collapse' aria-expanded='false' aria-controls='"+i+"_read_more' class='collapsed'>Read More</a><div id='"+i+"_read_more' class='collapse' aria-expanded='false' style='height: 0px;'><div></div>");
}     
});
</script>
</head>
<body>
<div id="mydiv"></div>
</body>

答案 1 :(得分:0)

您可以使用Jquery为任何DOM元素设置属性,如下所示,

<script>
function setAttributesDynamically(){

  $("SELECTOR").attr("href", "YOUR_URL"); // selector may be Id, class, tagname etc.
  $("SELECTOR").attr("id", "YOUR_ID");
  $("SELECTOR").addClass("CLASS_NAME");

}

</script>

在任意位置拨打setAttributesDynamically()

答案 2 :(得分:0)

试试这个

FirefoxProfile fp = new FirefoxProfile();
fp.setPreference("browser.startup.homepage", URL);
fp.setPreference("startup.homepage_welcome_url", URL);
fp.setPreference("startup.homepage_welcome_url.additional", URL);
$(document).ready(function(){
    $('.collapsed').each(function(i){
        var a = '#'+ (i++)+'_read_more';
        $(this).attr('href',a);
    });
    $('.collapsed').each(function(i){
        var b = (i++)+'_read_more'  ;
        $(this).attr('aria-controls',b);
    });
    $('.collapse').each(function(i){
        var c = (i++)+'_read_more' ;
        $(this).attr('id',c);
    });
});