zoukankan      html  css  js  c++  java
  • vue在v-html的html字符串中绑定事件

    最近做项目,使用得vue作为基础框架。有这样一个需求,需要给返回来的富文本绑定事件,搜了一下众说纷纭。自己摸索了和总结出一套比较好用得方式。

    利用JavaScript事件捕获,通过给使用v-html的标记绑定click事件,捕获到点击的标记。从而实现vue动态绑定dom元素事件的效果;

    代码如下:

    富文本数据:

    "richTextContent": "<p class='testssss' data-innervalue='sadsadsa' data-value='{nasdlkashdashdkjsahdksd}'><span style="font-size: 14px;"></span>Some Wi‑Fi networks are open and you can simply connect for internet access. Other Wi‑Fi networks are secure and require you to enter a password. Contact the Wi-Fi network&#39;s owner for the password.</p><p>To search for and connect with available Wi-Fi networks:</p><ol class=" list-paddingleft-2"><li><p>Swipe down from the top of your screen to open <strong>quick settings</strong> and then:</p></li><ul class=" list-paddingleft-2"><li><p>Android 9: Touch &amp; hold <img src="https://help.motorola.com/hc/images/global/qs_wifi_on_90.png"/>.</p></li><li><p>Android 8: Touch <strong>Wi Fi &gt; More settings</strong></p></li><li><p>Android 7: Touch <strong>Wi Fi</strong>.</p></li></ul><li><p>Turn Wi-Fi on <img src="https://help.motorola.com/hc/images/global/slider_on.png"/>.</p></li><li><p>Touch the Wi-Fi network you want to connect to.</p></li><li><p>If the network is a secure one, enter the password.</p></li></ol><p>Make sure you enter the password correctly. Touch <strong>Show password</strong> to see what you’re typing.</p><p>When your phone is connected, <img src="https://help.motorola.com/hc/images/global/i_wifi_min.png"/> appears in the status bar. If the connection is poor, <img src="https://help.motorola.com/hc/images/global/i_wifi_poor.png"/> appears in the status bar.</p>",

    vue模板写法

    <div class="richText" v-html="richTextContent" @click="test"></div>

    script方法

    test (event) {
       console.log(event.target.className) // testssss
       console.log(event.target.nodeName) // p
       if (event.target.nodeName === 'p' && event.target.className === 'testssss') {
         // 获取触发事件对象的属性
         alert('a')
       }    
    }

    最终效果

  • 相关阅读:
    9个offer,12家公司,35场面试,从微软到谷歌,应届计算机毕业生的2012求职之路(转)
    Path Sum(参考别人,二叉树DFS)
    tcp/ip
    常见Unix指令
    Pascal's Triangle II
    Implement strStr()
    LeetCode总结
    从LLVM源码学C++(一)
    面试题:1到N中,1出现的次数
    面试题:数组划分成两个子数组,和的差值的绝对值最小
  • 原文地址:https://www.cnblogs.com/wangweizhang/p/12067700.html
Copyright © 2011-2022 走看看