How do you convert a jQuery object into a string?

前端 未结 12 2033
臣服心动
臣服心动 2020-11-22 15:07

How do you convert a jQuery object into a string?

12条回答
  •  长发绾君心
    2020-11-22 15:39

    If you want to stringify an HTML element in order to pass it somewhere and parse it back to an element try by creating a unique query for the element:

    // 'e' is a circular object that can't be stringify
    var e = document.getElementById('MyElement')
    
    // now 'e_str' is a unique query for this element that can be stringify 
    var e_str = e.tagName
      + ( e.id != "" ? "#" + e.id : "")
      + ( e.className != "" ? "." + e.className.replace(' ','.') : "");
    
    //now you can stringify your element to JSON string
    var e_json = JSON.stringify({
      'element': e_str
    })
    

    than

    //parse it back to an object
    var obj = JSON.parse( e_json )
    
    //finally connect the 'obj.element' varible to it's element
    obj.element = document.querySelector( obj.element )
    
    //now the 'obj.element' is the actual element and you can click it for example:
    obj.element.click();
    

提交回复
热议问题