问题
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