为此创建动态<a href=""> link with JS &amp; JQUERY

时间:2017-02-16 10:42:14

标签: javascript jquery html

i need some help!

I have HTML code Like this:

<div id="Text0">
<a href="x">
<span  class="farbig">Jenkins</span> 
<span  class="farbig1">CMS</span>
</a>

And this is my JS Code:

var jenkinsinstances={};
jenkinsinstances.cupo={"href":"localhost:2000", "imgsrc":"http://s3.kaercher.../jenkins-cupo.png"};

I want to readout the JS code with JQUERY and insert it to all [a href = " "], creating a dynamic link.

Thank you very much!

2 个答案:

答案 0 :(得分:0)

var jenkinsinstances = {
  "href": "localhost:2000",
  "imgsrc": "http://s3.kaercher.../jenkins-cupo.png"
};

$("a").each(function(i, v) {

  console.log(jenkinsinstances.href)
  $(this).attr('href', jenkinsinstances.href)
})
$("img").each(function(i, v) {

  $(this).attr('src', jenkinsinstances.imgsrc)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Text0">
  <a href="x">a</a>
  <img src="X" />
  <span class="farbig">Jenkins</span>
  <span class="farbig1">CMS</span>
  </a>

使用.attr()设置锚点和img的属性,然后在对象上选择它

答案 1 :(得分:0)

这就像只有一个anchor标签一样。

$('#Text0 a').attr('href', jenkinsinstances.cupo.href);

&#13;
&#13;
var jenkinsinstances = {};
jenkinsinstances.cupo = {
  "href": "localhost:2000",
  "imgsrc": "http://s3.kaercher.../jenkins-cupo.png"
};

console.log($('#Text0 a').attr('href', jenkinsinstances.cupo.href).attr('href'));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Text0">
  <a href="x">
    <span class="farbig">Jenkins</span>
    <span class="farbig1">CMS</span>
  </a>
</div>
&#13;
&#13;
&#13;