[英]Add href to .text output in jquery
I'm using firebase to get this data, I'd like to add href tags to message.userName output 我正在使用firebase来获取这些数据,我想在message.userName输出中添加href标签
$('#winners').text('Winner:' + ' ' + message.userName + ' ' + ' '+ 'score:' + ' ' + message.score + ' ' + ' '+ 'Start time:' + ' ' + message.startTime + ' ' + ' '+ 'End time:' + '' + message.endTime );
I've tried 我试过了
$('#winners').text('Winner:' + ' ' + '<a href=\"scoreTracker.php?id='+message.userID +'\"> + ' message.userName + ' ' + ' '+ 'score:' + ' ' + message.score + ' ' + ' '+ 'Start time:'
+ ' ' + message.startTime + ' ' + ' '+ 'End time:' + '' + message.endTime + '<\a>' );
To avoid XSS attacks (among other weird problems), append an anchor element and set its text. 为了避免XSS攻击(以及其他奇怪的问题),请附加一个锚元素并设置其文本。 This means you don't have to worry about escaping anything. 这意味着您不必担心逃避任何事情。
$('#winners').append([
'Winner: ',
$('<a>')
.attr('href', 'scoreTracker.php?id=' + encodeURIComponent(message.userId))
.text(
message.userName + ' score: ' + message.score + ' Start time: ' + message.startTime + ' End time: ' + message.endTime
)
]);
If your HTML gets much more complicated, might I suggest a JavaScript template engine? 如果您的HTML变得更复杂,我可以建议使用JavaScript模板引擎吗? I use Swig for most projects, but there are many choices. 我在大多数项目中使用Swig ,但有很多选择。
you have to use append() , or html() 你必须使用append()或html()
$('#winners').append('Winner:' + ' ' + message.userName + ' ' + ' '+ 'score:' + ' ' + message.score + ' ' + ' '+ 'Start time:' + ' ' + message.startTime + ' ' + ' '+ 'End time:' + '' + message.endTime );
this may help you to understand better : 这可能有助于您更好地理解:
http://api.jquery.com/category/manipulation/dom-insertion-inside/ http://api.jquery.com/category/manipulation/dom-insertion-inside/
Both @Brad and @ProllyGeek are correct -- but @Brad's solution is best given the potential risk of XSS attacks. @Brad和@ProllyGeek都是正确的 - 但@ Brad的解决方案最好考虑到XSS攻击的潜在风险。 Here is his code, just cleaned up a bit for better readability. 这是他的代码,只是为了更好的可读性而清理了一下。 :) :)
$('#winners').append([
'Winner: ',
$('<a />')
.attr('href', 'scoreTracker.php?id=' + encodeURIComponent(message.userId)
.text(message.userName + ' score: ' + message.score + ' Start time: ' + message.startTime + ' End time: ' + message.endTime)
]);
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.