[英]jQuery create a with href attribute
I just faced a very serious issue with jQuery.我刚刚遇到了一个非常严重的 jQuery 问题。 I wanted to create an element using jQ.
我想使用 jQ 创建一个元素。 Like the regular way I tried:
jQuery('<a href="http://www.google.com"></a>');
就像我尝试的常规方式一样:
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=""
.事实证明,我无法创建包含
href=""
HTML 元素。
jQuery('<a id="id5" name="link"></a>');
will workjQuery('<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.
我有一个返回准备好的 HTML 代码的函数。 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.
我不知道返回的 HTML 是否是相同的结构。 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.经过一些进一步的反复试验,结果证明这是一个关于 Safari 的问题。 In Chrome my code works great.
在 Chrome 中,我的代码运行良好。
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>" + html + "</div>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.