How to correclty assign string which contains spaces to data attribute?

萝らか妹 提交于 2019-12-10 12:25:21

问题


I've got stuck at one issue that, I am getting string from server side as one bottle only. I am assigning that string to data attribute like

var uom = serverSideValue // Contains ["one bottle only"]
<div class="uomClass" data-uom="+ JSON.stringify(uom) +"></div>

But when I inspect that element in developer tools, it is appearing like

data-uom="["one" only"]

If not JSON.stringify

data-uom="one" only

When I am trying to access uom, like below

$('.uomClass').data('uom') 

above line of code giving result as only one instead of one water bottle

What I am doing wrong here. I am dynamically constructing the uom html above. Please guide me through the right way. Thank you.


回答1:


I solved the issue by taking Rory McCrossan suggestion in the comments section below the question. I've used encodeURIComponent() and decodeURIComponent()

HTML Code

var uom = serverSideValue // Contains ["one bottle only"]
<div class="uomClass" data-uom="+ encodeURIComponent(uom) +"></div>

jQuery Code

var $uom = decodeURIComponent($('.uomClass').data('uom'))

Now I am getting the correct results. Thank you Rory McCrossan for your suggestion.



来源:https://stackoverflow.com/questions/48925098/how-to-correclty-assign-string-which-contains-spaces-to-data-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!