美文网首页
从字符串HTML标签读取关键的css属性的值

从字符串HTML标签读取关键的css属性的值

作者: 地主家也没余粮叻 | 来源:发表于2018-09-11 00:43 被阅读0次

    需求:可以选择富文本编辑,也可以选择输入框来编辑问题答案,保存的时候选择的是什么,再次进来就展示对应页签的数据,切换页签就清空另一个,只能两选一

    需求图

    因为传给后端是一个字符串,编辑的时候需要再次从字符串里面拿到对应的自定义属性的值,展示在输入框中,
    传给后端,直接用es6 字符串模板语法,通过对象赋值,这没什么好说的,编辑的时候从字符串里面取值,拿到对象这婶的(需要取值的已标出):

    const content = '<div class="MN_gusList" style="box-sizing: border-box; color: rgb(0, 140, 238); cursor: pointer; font-family: "Microsoft YaHei", Arial, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;" data-qaId="b9ae933b-0d13-455d-b6b6-0e7beef59f0d" data-title="测试问题类型勿删" data-qaType="3">1. 别名1 <div>'

    拿到这个需求第一反应是用正则来匹配,无奈正则太渣了,最后从别人那得到启发,通过创建一个对象,然后通过querySelect拿到对应节点对象的值,querySelect是js对象的一个方法,而这个对象就是节点对象,我们完全可以通过原生js 对象创建一个节点对象,并不需要将它添加到页面中,就可以方便的利用js的一些原生或者其他方法,实现如下:
    const createDiv = document.createElement('div')
    createDiv.innerHTML ='<div class="MN_gusList" style="box-sizing: border-box; color: rgb(0, 140, 238); cursor: pointer; font-family: "Microsoft YaHei", Arial, sans-serif; font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;" data-qaId="b9ae933b-0d13-455d-b6b6-0e7beef59f0d" data-title="测试问题类型勿删" data-qaType="3">1. 别名1</div>'
    const target = createDiv.querySelect('#biguiyuan')
    console.log(target.getAttribute('data-qaId'),target.innerText)
    总结:想的太少,思想太狭隘了,多做多看多想,
    附录链接:

    相关文章

      网友评论

          本文标题:从字符串HTML标签读取关键的css属性的值

          本文链接:https://www.haomeiwen.com/subject/satygftx.html