jQuery追加:无法正确引用引号
Posted
技术标签:
【中文标题】jQuery追加:无法正确引用引号【英文标题】:jQuery append: can't get the quotes right 【发布时间】:2014-10-07 20:12:22 【问题描述】:我正在尝试向 div 添加一些 html,但无法正确引用引号...这是我认为可行的方法,但没有...:
success: function (data)
id = data.photo_id;
$("#successtext").append('<a href="https://www.theurl.com/' + id + '" data-role="button">The link</a><a href="#" data-role="button">Log Out</a>');
$("#success").show();
$("#uploading").hide();
$("#turn").hide();
turnable = 0;
如您所见,这是 Ajax 调用的一部分。请注意,附加确实有效,只是不适用于右键标记。
注意:第一个链接链接到例如https://www.theurl.com/223424324
我做错了什么,为什么?谢谢!
【问题讨论】:
你看到了什么错误? 不是错误,只是标记错误。 a href 应该是一个按钮(jQuery mobile -> data-role="button"),但它只显示两个文本超链接。 【参考方案1】:现有:
'<a href="https://www.theurl.com/"'+id+'"
在向其添加 id
之前,您要结束 href
属性的引号,而在添加 id
之后,您又要添加引号,这会破坏事情。
正确:
'<a href="https://www.theurl.com/'+id+'"
基本的事情是,当您在 ajax 请求之后附加文本时,jquery mobile 不会在您的链接周围创建自己的 DOM 元素以使其看起来像一个按钮。因此,为此我们需要允许 jquery mobile 在附加文本后创建其 DOM。 试试下面的函数。
$.mobile.activePage.find('#successtext').trigger('create');
Fiddle
【讨论】:
不幸的是,它不能解决我的问题(参见我对 Sudhir 的回答)【参考方案2】:你在www.theurl.com/"'+id+'"
有额外的报价,改为:
$("#successtext").append('<a href="https://www.theurl.com/'+id+'" data-role="button">The link</a><a href="#" data-role="button">Log Out</a>');
更新::在追加后调用.trigger('create')
$("#successtext")
.append('<a href="https://www.theurl.com/'+id+'" data-role="button">The link</a><a href="#" data-role="button">Log Out</a>')
.trigger('create');
演示:: jsFiddle
【讨论】:
感谢您的回复,我尝试了您的代码,但它不能解决我的问题。我仍然得到文本超链接,而不是按钮。就好像它失去了数据角色或其他东西......(不过,按钮在没有这个附加东西的情况下也能工作)。 @binoculars 你在什么时候附加标签,你能显示更多的代码..! @binoculars 您需要在附加标签后调用 .trigger('create') 以使其适用于动态添加..查看我的更新答案【参考方案3】:试试这个:
JS:
$('#successtext').append('<a href="https://www.theurl.com/'+id+'" data-role="button">The link</a><a href="#" data-role="button">Log Out</a>');
【讨论】:
【参考方案4】:jsFiddle Demo
正如其他人指出的那样,问题在于您的 href 有两个右引号(基本上是 href="...""
)。然而,它确实突出了您在使用 jQuery 附加长 html 片段之前手动将长 html 片段填充到 JS 字符串中可能遇到的问题。考虑改为将 html 元素视为对象,并使用 jQuery 构造它们:
$("#successtext").append($("<a />",
href: "https://www.theurl.com/" + id,
"data-role": "button",
text: "The link"
), $("<a />",
href: "#",
"data-role": "button",
text: "Log Out"
));
【讨论】:
从来没有想过,我以后一定会记住的。谢谢!虽然没有解决我的问题,解决方法是我必须在追加后添加.trigger('create')
。以上是关于jQuery追加:无法正确引用引号的主要内容,如果未能解决你的问题,请参考以下文章