简体   繁体   中英

jQuery create a with href attribute

I just faced a very serious issue with jQuery. I wanted to create an element using jQ. Like the regular way I tried: jQuery('<a href="http://www.google.com"></a>');

But this does not work. So I tried several different element types and attributes. It turned out that I am not able to create elements with HTML containing href="" .

  • jQuery('<a id="id5" name="link"></a>'); will work
  • jQuery('<a id="id5" name="link" href=""></a>'); will not work.

Is there any know issue or workaround for this problem?? Thanks in advice…

EDIT:

To clarify: I don't want to create an element using known attributes. I have a function that returns a ready HTML code. I want to use this code to extract the image tag and then get its attributes. I don't know if the returned HTML will be the same structure. I just know that it contains an image tag. Here is the code I used before:

jQuery(html).find('img:first').attr('class').match(/\image-(\d+)\b/)[1]

I would use different approach:

var newLink = $("<a />", {
    id : "id5",
    name : "link",
    href : "http://www.google.com/",
    text : "some text"
});

This should work (tested):

var thelink = $('<a>',{
    text: 'linktext',
    title: 'some title',
    href: 'somelink.html'
}).appendTo('body');
var a = document.createElement('a');
$(a).attr('href','index.html').attr('id','xyz').addClass('example');

After some further trial & error it turned out that this is an issue regarding Safari. In Chrome my code works great.

I finally got a fix. I just wrap the HTML string I'm getting back from the function into <div> tags:

html = "<div>" + html + "</div>";

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