如何从 RJS 模板更改 html 标签属性值?
是否可以从 RSJ 模板更改 html 标签属性值? 我知道有一个 page.replace_html 方法,但在我的情况下它不是很有用,因为我有各种属性的冗长值(例如 alt、图像标题)。 我想要的是更改 RJS 中 img 标签的 src 属性。 这可能吗?
谢谢。
Is it possible to change a html tag attribute value from an RSJ template?
I know that there is a page.replace_html method, but it is not very useful in my case, since I have lengthy values of various attributes (such as alt, title of an image).
What I want is change src attribute of a img tag in RJS.
Is that possible at all?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑:我的第一次尝试没有成功,但这次成功了。
EDIT: My first attempt didn't work, but this one does.
对 Can 的答案稍作修改。 正如建议的,
转换为 JS:
这适用于某些具有直接 JS DOM 变量访问权限的属性,但许多属性则不然。 幸运的是,RJS 非常擅长重写 JS 方法调用:
翻译为 JS:
你应该可以开始了。
小更新:如果您想要 IE 兼容性,您可能需要使用 write_attribute。
小更新:在上面,如果 [:src] 和 :attrib 是静态的,它们可能是更好的样式。
Slight modification to Can's answer. As suggested,
translates to JS:
This will work for some attributes that have direct JS DOM variable access, many don't. Luckily RJS is pretty good at rewriting JS method calls:
translates to JS:
and you should be good to go.
Small update: you may want to use write_attribute instead if you want IE compatibility.
Small update: in the above, [:src] and :attrib would probably be better style if these are static.
根据 Rails 设置,上面的代码可能仅在排除 page_update 开始行和结束行时才有效 - 我在 Windows 7 上的 mongrel 上运行 Rails,并将 page[element][attribute] 代码放在其自己的外部update_page 块的,工作正常,但将其包含在块内会破坏代码。
Depending on the Rails setup, the code above might work only if you exclude the page_update start and end lines -- I'm running Rails on mongrel on Windows 7, and putting the page[element][attribute] code on its own, outside of the update_page block, works fine, but including it inside the block breaks the code.