简体   繁体   中英

how to add (href) in (a) by jquery?

how to add (URL) this in HTML(a)

var gm = document.body.innerHTML.match(/id=\d+.+على.+id=\d+/g);


for(var i=0;i<10;++i) 
window.open('/game.php?village=' + gm[i].match(/id=(\d+)/g)[0].replace("id=",'') + '&screen=place&target=' + gm[i].match(/id=(\d+)/g)[1].replace("id=",''));

HTML

<b id='ABC'>
<a id='f' href ='' >ABC1</a>
<a id='f' href ='' >ABC2</a>
<a id='f' href ='' >ABC3</a>
<a id='f' href ='' >ABC4</a>
<a id='f' href ='' >ABC5</a>
</b>

but i do not want use : => window.open

i want use (var) like this :

var ss = '/game.php?village=' + gm[i].match(/id=(\d+)/g)[0].replace("id=",'') + '&screen=place&target=' + gm[i].match(/id=(\d+)/g)[1].replace("id=",'');

In order to add her (href)

by jquery or javascript

<b id='ABC'>
<a id='f' href ='' >ABC1</a>
<a id='f' href ='' >ABC2</a>
<a id='f' href ='' >ABC3</a>
<a id='f' href ='' >ABC4</a>
<a id='f' href ='' >ABC5</a>
</b>

i use this

$("#abc ").each(function(){
$(this).find("a").attr("href",ss);

});

but Error ?

how ? and thanks

  • $("#abc ").each() iterates over element having id abc : iterating over an id selector is pointless since id should be unique in a document. You should iterate over the <a> elements instead
  • Selectors are case sensitive. id in your HTML is ABC and in your selector you're using abc . You should use the correct id.

     $("#ABC a").each(function () { $(this).attr("href", ss); }); 

side notes:

  • Multiple elements should not have the same id : you should use a class instead...

  • jQuery setter methods generally iterates over the collection upon which they are called, so unless you have to perform multiple operations, no need to manually iterate. $("#ABC a").attr("href", ss); will do the same.

$("#abc a").each(function(){
$(this).attr("href",ss);
});

You have to iterate anchor tag/.

There are 2 ways to do this.

By class name:

Change your anchor tag ID to CLASS, like this:

...
<a class='f' href ='' >ABC1</a>
...

Change jQuery code to:

$(".f ").attr("href",ss);

By child/parent:

$("#abc").find('a').attr("href",ss);

NOTE: DOM element IDs should be unique. No two elements should have the same ID. You can assign the same class to multiple elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM