简体   繁体   中英

How to change html tag attribute value from RJS template?

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.

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. As suggested,

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

translates to JS:

$('image_id').src = new_image_url

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:

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

translates to JS:

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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