jQuery 的 attr() 转义 & 符号
所以我试图通过 javascript 动态设置图像 src 属性,如下所示:
var url = 'query.php?m=traffic&q=getgraph&id='+pipeId+'&start=-3h';
console.log(url);
$('#3h').attr('src',url);
问题是,它显示如下 query.php?m=traffic&q=getgraph&id=1&start=-3h< /code> 在控制台中,#3h 图片元素的实际设置 src 为
query.php?m=traffic&q=getgraph&id=1&start=-3h
code>
然后,当然,它不起作用。如何避免 jQuery 的 attr() 方法的字符转义?关于我应该如何实现目标的任何其他建议也非常受欢迎。
So i'm trying to set an image src attribute dynamically via javascript like so:
var url = 'query.php?m=traffic&q=getgraph&id='+pipeId+'&start=-3h';
console.log(url);
$('#3h').attr('src',url);
The problem is, it shows up like so query.php?m=traffic&q=getgraph&id=1&start=-3h
in the console, the the actual set src for the #3h image element is query.php?m=traffic&q=getgraph&id=1&start=-3h
And then, of course, it doesn't work. How do I avoid jQuery's attr() methods' character escaping? Any other suggestions on how should I achieve my goal are very welcome as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我在您的代码中看到的唯一问题是您的 ID 属性以数字开头,这在 HTML4 中无效。
您应该将元素上的 ID 更改为以字母开头,例如
h3
The only issue that I see in your code is that your ID attribute is starting with a number, which is invalid in HTML4.
You should change the ID on the element to begin with a letter, like
h3
对我来说它有效:
http://jsfiddle.net/y249K/
For me it's working:
http://jsfiddle.net/y249K/
您可以在将数据写入属性之前
转义
数据。试试这个小提琴
然后
You can
escape
the data before writing it to an attribute.Try out this fiddle
then
您可以避免使用 jQuery,而是使用本机 JavaScript/DOM 函数:
document.getElementById('3h').src = url;
You could avoid using jQuery for this and use native JavaScript/DOM functions instead:
document.getElementById('3h').src = url;
如果它不起作用,则不是因为&符号被转义了。作为 HTML 元素中的属性,所有 XML 实体都需要转义:
例如,如果我有
index.php?foo=bar&buzz=baz
,并且我想要一个a
元素定位该页面,我需要像这样设置锚点:href 将被解码为:
index.php?foo=bar&buzz=baz
我会看到如果我找不到适合您的相关文档。
If it doesn't work, it's not due to the ampersands being escaped. As an attribute in an HTML element, all XML entities need to be escaped:
As an example, if I had
index.php?foo=bar&buzz=baz
, and I wanted to have ana
element target that page, I would need to set the anchor like so:The href would get decoded as:
index.php?foo=bar&buzz=baz
I'll see if I can't find the relevant documentation for you.