I'm trying to move a link around but when I try to include it within a string it doesn't work. If I remove the string it does though. Why is this happening and how do I fix it?

$(document).ready(function(){
    var link = $('a');

    //Remove the '<div>'s and it works...
    $('div').after('<div>'+link+'</div>'); 
});

See pen for an example: http://cdpn.io/AKnsL

Thanks.

ED: I probably should of noted that this is a simplified version of what I am trying to do, I'm trying to rebuild a menu (don't ask why...) and I have each link assigned to a variable which is then added in place to a rather long string of divs and such, which is all then added in "after" another div. I only mention in case it changes the way this could be done, and I should mention I'm no JS pro :)

Thanks#2!

有帮助吗?

解决方案 2

$("a") is actually an object, not a string. If you use $("div").after(link), jQuery will work out that you actually want to append the DOM element.

The problem comes in when you do '<div>' + link + '</div>', where JavaScript is creating the string before jQuery gets involved. this is where [object Object] comes from - this is JavaScript's way of creating a sensible String value for an object. What's being evaluated is $("div").after("<div>[object Object]</div>");

You can get around this by first creating your new div, appending the a to that, then appending your new div to the original.

$(document).ready(function() {
  var link = $("a"),
      new_div = $("<div />").append(link);

  $("div").after(new_div);
});

其他提示

The issue is because a jQuery selector, such as $('a') returns an object, and appending a string and an object results in what you've seen.

If you want to move the link to a different element in the DOM, use append():

var link = $('a');
$('div').append(link);

You could use:

$('div').after('<div/>',{html:link}); 

Try:

div.innerHTML=""+$('a').attr("href").toString()+"";

or:

var str="";
str+=""+$('a').attr("href").toString()+""; // str will contain links href in it

That will append text to div as a string with its href as text to be appended.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top