简体   繁体   中英

Javascript: Change the ID of a div element and save the value

I have this code:

<img src="{$img_dir}/product_grid_view.png" class="pgrid" title="Grid View" onclick="document.getElementById('product_list').id = 'product_grid'; return false"></img>
<img src="{$img_dir}/product_list_view.png" class="plist" title="List View" onclick="document.getElementById('product_grid').id = 'product_list'; return false"></img> 

The following code works well and does its job but the main problem is that it doesn't keep the new value saved after I refresh the page and keeps reverting to default value product_list which is mentioned in a .tpl file as the following statement: <div id=product_list" class="clearfix"> .

Any suggestions on this matter would be greatly appreciated!

If you want data to persist between page refreshes, then you have to store it somewhere persistent.

That could be somewhere that is accessible client side (eg in a cookie) and then reapplying the changes based on the data there when the page reloaded.

Alternatively, you could use Ajax to inform the server of the change and have the server store the data somewhere (such as in a database) and generate different based on that data when the page is requested.

(The id, however, is a terrible thing to change dynamically).

Short answer: Not possible (at least, not as in your example).

Javascript is client side and when you refresh the page will be created server side.

If you really want this you should save the value server-side (by using AJAX ) and use this value when the page is reloaded. But I really don't think you want to be doing that just to swap id's (which is strange in the first place).

What you are doing happens only on client side. It does not change your .tpl file. In order to get it updated you should send information on server, for instance with ajax , and save new id into database using PHP (as I understand, that is server side language you are using) and populate it in your .tpl file next time page is loaded.

At the same time - not clear why do you need to change an ID of an element that way. Looks like you are doing something wrong.

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