开发者

Getting value from key pair value into appended property using jQuery

开发者 https://www.devze.com 2022-12-25 05:08 出处:网络
How do I get the value from a key pair value into the rel property of an anchor tag? When I split the code to put the value in the correct place it doesn\'t work, the end of the a t开发者_如何转开发a

How do I get the value from a key pair value into the rel property of an anchor tag?

When I split the code to put the value in the correct place it doesn't work, the end of the a t开发者_如何转开发ag would appear on screen instead value wouldn't be applied. When I look at the resulting code in console in Firebug the rel and href swapped order so the rel is first.

The 'key' should be and is in the correct location but the 'value' needs to be applied to the rel attribute.

What am I doing wrong?

$(function() {
 var obj = {"firstThing":"4","secondThing":"6","aThirdThing":"2","anotherThing":"3","followedByAnother":"4"};

 $.each(obj, function(key,value) {

  $('#newmine').append("<li class='tagBlocks'>","<a href='#' rel=''>",value," ",key);
 });
});


I would change it up a bit to use the jQuery functions instead of building the string, like this:

$(function() {
 var obj = {"firstThing":"4","secondThing":"6","aThirdThing":"2","anotherThing":"3","followedByAnother":"4"};

 $.each(obj, function(key,value) {  
    $("<li class='tagBlocks'></li>").append(
        $("<a href='#'></a>").attr('rel', value).text(key)
    ).appendTo("#newmine");
 });
});​

The swap occurs because well...it's the javascript and that's the DOM. The order doesn't matter, it's just a list of properties, so whatever the browser processes first may or may not appear first in whatever debugging tool you use. Whatever the position, the effect is the same, so the order you see in the debugger may be different for every single browser...in this case that's ok :)


Look at this more closely:

"<li class='tagBlocks'>","<a href='#' rel=''>",value," ",key

You have put value after the > which closes the a tag.
I just would generate one string and append it:

'<li class="tagBlocks"><a href="#" rel="' + value + '">' + key + '</a></li>'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号