代码之家  ›  专栏  ›  技术社区  ›  Hello Universe

如何使用jQuery获取字符串中的值?

  •  0
  • Hello Universe  · 技术社区  · 7 年前

    我有一个字符串如下

    <?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>
    

    我想获取附件中的值,也就是example\u image\u 1\u rapital\u HD.jpg 如何使用jQuery实现这一点?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Osama    7 年前

    使用$.parseXML()

    var xml ="<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>";
    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc ),
    $title = $xml.find( "Attachments" );
    console.log($title.text());
    
        2
  •  1
  •   CertainPerformance    7 年前

    通过将字符串传递给 $ ,然后就可以得到 Attachments 具有的节点 .find('Attachments').text()

    const htmlStr = '<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>';
    
    console.log($(htmlStr).find('Attachments').text());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    但是请注意,完全不需要依赖jQuery这样的大型库来进行XML解析—您可以使用内置的 DOMParser 取而代之的是:

    const htmlStr = '<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>';
    
    const doc = new DOMParser().parseFromString(htmlStr, 'text/html');
    console.log(doc.querySelector('Attachments').textContent);