如何将包含空格的字符串赋值给数据属性? [英] How to correclty assign string which contains spaces to data attribute?
问题描述
我遇到了一个问题,我从服务器端获取字符串仅一瓶。我将该字符串分配给数据属性,如
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"]
如果不是JSON.stringify
If not JSON.stringify
data-uom="one" only
当我尝试访问uom时,如下所示
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
我在这里做错了什么。我正在动态构建上面的uom html。请引导我通过正确的方式。谢谢。
What I am doing wrong here. I am dynamically constructing the uom html above. Please guide me through the right way. Thank you.
推荐答案
我在下面的评论部分采取了 Rory McCrossan 的建议解决了这个问题。题。我使用了 encodeURIComponent()和 decodeURIComponent()
I solved the issue by taking Rory McCrossan suggestion in the comments section below the question. I've used encodeURIComponent() and decodeURIComponent()
HTML代码
var uom = serverSideValue // Contains ["one bottle only"]
<div class="uomClass" data-uom="+ encodeURIComponent(uom) +"></div>
jQuery代码
var $uom = decodeURIComponent($('.uomClass').data('uom'))
现在我得到了正确的结果。感谢 Rory McCrossan 提出建议。
Now I am getting the correct results. Thank you Rory McCrossan for your suggestion.
这篇关于如何将包含空格的字符串赋值给数据属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!