简体   繁体   English

如何从 RJS 模板更改 html 标记属性值?

[英]How to change html tag attribute value from RJS template?

Is it possible to change a html tag attribute value from an RSJ template?是否可以从 RSJ 模板更改 html 标记属性值? 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).我知道有一个 page.replace_html 方法,但在我的情况下它不是很有用,因为我有各种属性的冗长值(例如 alt、图像的标题)。 What I want is change src attribute of a img tag in RJS.我想要的是更改 RJS 中 img 标签的 src 属性。 Is that possible at all?这有可能吗?

Thank you.谢谢你。

EDIT: My first attempt didn't work, but this one does.编辑:我的第一次尝试没有成功,但这次成功了。

update_page do |page|
  page['image_id']['src'] = new_image_url
end

Slight modification to Can's answer.对Can的答案稍作修改。 As suggested,正如建议的那样,

update_page do |page|
    page['image_id']['src'] = new_image_url
end

translates to JS:翻译成 JS:

$('image_id').src = new_image_url

This will work for some attributes that have direct JS DOM variable access, many don't.这适用于某些具有直接 JS DOM 变量访问权限的属性,但许多属性没有。 Luckily RJS is pretty good at rewriting JS method calls:幸运的是 RJS 非常擅长重写 JS 方法调用:

update_page do |page|
    page['image_id'].set_attribute('attrib', new_attrib_val)
end

translates to JS:翻译成 JS:

$('image_id').setAttribute('attrib', new_attrib_val)

and you should be good to go.你应该对go很好。


Small update: you may want to use write_attribute instead if you want IE compatibility.小更新:如果你想要 IE 兼容性,你可能想要使用 write_attribute。


Small update: in the above, [:src] and:attrib would probably be better style if these are static.小更新:在上面,如果是 static,[:src] 和:attrib 可能会更好。

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.根据 Rails 设置,上面的代码可能只有在排除 page_update 开始和结束行时才有效——我在 Windows 7 上的 mongrel 上运行 Rails,并将 page[element][attribute] 代码放在它自己的外部update_page 块的一部分,工作正常,但将其包含在块中会破坏代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM