使用 JQuery 操作 Rails HTML
我在让 ruby 解析 JQuery 时遇到问题。
例如,下面的代码行应该在 id 为“title”的 div 之后添加 @user 的用户名。
$('#title').after('<%= escape_javascript(@user.first.username') %>);
但是,我收到的输出是一个尚未解析的字符串,包含 <
我还没有在 Stack Overflow 上找到任何专门发布于此的内容,并且我已经关注了几个辅导不成功。
预先感谢您的帮助!
I am having issues getting JQuery to be parsed by ruby.
For instance, the following line of code is supposed to add the @user's username after the div with id 'title.'
$('#title').after('<%= escape_javascript(@user.first.username') %>);
However, the output that I receive is a string that hasn't been parsed at, complete with <
I haven't found anything specifically posted on this on Stack Overflow and I've followed several tutorials unsuccessfully.
Thanks in advance for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
erb 在页面加载之前被解析,因此这是在 javascript 执行期间插入 erb 代码,而根本不会被解析。一种更好的方法是插入 JS 来设置一个变量,然后使用该变量:
erb is parsed before the page loads, so this is inserting the erb code during javascript execution, which doesn't get parsed at all. A better way to do this one would be to insert JS to set a variable, and then use that variable:
我认为你不应该采取这种方法...在你的 erb 中放置脚本标签在我看来是一种味道。您最好使用用户名和 'user_name' id 创建一个隐藏输入字段,然后在 app.js 中使用不显眼的 js 来获取字段值并附加它。
I would argue you should not take this approach... Placing script tags in your erb is a smell IMO. You would be better off creating a hidden input field with the username and an id of 'user_name' and then using unobtrusive js in your app.js to get the field value and append it.