简体   繁体   English

JS-将字符串从数据属性转换为对象

[英]JS - converting string from data-attribute into object

I have a string like: 我有一个像这样的字符串:

<span class="someClass" id="skAdmin" data-options='{
   "elmsList" : {
      "#skAdmin" : {
         "action" : "replace",
         "replaceWith" : "<input class=\"form-control\">"
         }
      }
   }'>Name</span>  

Now (when i make a click on this span ) I need to replace this element ( span ) by element in data-options ( input ). 现在(当我单击此span时 )我需要用data-options( 输入 )中的元素替换此元素( span )。 And at the same time i need to add all span attributes to input element, but input is just a text (not an object). 同时,我需要将所有span属性添加到input元素,但是input只是文本(不是对象)。 How can I convert this to object? 如何将其转换为对象?

Use JSON.parse() to retrieve an object: 使用JSON.parse()检索对象:

var obj = JSON.parse( document.querySelector( '#skAdmin' ).dataset.options );

// or

var obj = JSON.parse( document.getElementById( 'skAdmin' ).dataset.options );

Edit 编辑

As the comments note, if you are already using jQuery, all data-* attributes will already be parsed into jQuery's data object . 如注释所示,如果您已经在使用jQuery,则所有data-*属性都将被解析为jQuery的data对象 So you can access it by just using: 因此,您可以通过以下方式访问它:

var obj = $( '#skAdmin' ).data( 'options' );

You do not need to parse this value as jQuery will have already done this for you when it stored it in it's in-memory cache. 您不需要解析该值,因为jQuery将其存储在内存中的缓存中时已经为您完成了此操作。 Therefore you can access it like an object: 因此,您可以像访问对象一样访问它:

$('.someClass').click(function() {
    var replaceWith = $(this).data('options').elmsList['#skAdmin'].replaceWith;
    $(this).replaceWith(replaceWith)
});

Example fiddle 小提琴的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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