jq 关于this与e.target区别

本文通过实例对比了JavaScript中事件处理函数内的this关键字与e.target属性的区别,阐述了两者在事件冒泡过程中的不同行为,对于理解DOM事件处理至关重要。

在编写事件函数时可以传入一个event参数,even参数可以使用一个target属性如even.target用以调用,其作用是指向返回事件的目标节点(触发该事件的节点),这与this是有区别的。
在js中事件属性是会冒泡的,所以在这情况下,如果选用this,那么this是随时变化的,它指向的总是当前触发的事件,而even.target则是仅仅指向触发该事件的节点。

举例子说明:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>e.target</title>
    <script src="jquery-3.2.1.js"></script>
</head>
<body>
<div id="temp"></div>
<ul class="JQ-content-box" style="padding:20px; background:#FFFFFF">
    <li>第一行
        <ul>
            <li>这是公告标题1</li>
            <li>这是公告标题2</li>
            <li>这是公告标题3</li>
            <li>这是公告标题4</li>
        </ul>
    </li>
</ul>
<script>
    $(function(){
        $("li").on("click",function(e){
            alert('e.target'+e.target.innerText);
            alert('this'+this.innerText);
            $("#temp").html("clicked: " + e.target.nodeName);
            $(this).css("color","#FF3300");
            $(e.target).css("color",'blu');
        })
    });
</script>
</body>
</html>

上述的例子可以发现,绑定的事件是一个冒泡事件,即假如点击“公告标题”的li,它会先触发自身的click事件,然后因事件冒泡再触发因父元素也绑定的click事件。
所以此时弹出的窗口共有4次,每两次为一组代表子元素与父元素,其中e.target一直指向触发该事件的节点,而this则随着事件的冒泡而不断变化。

注意:this与e.target是JavaScript对象,(this)(this)与(e.target)是jQuery对象

<template> <div class="insure-fill"> <div class="main"> <group class="gap"> <div class="card"> <p><span style="color: red;">*</span>请上传您的保费银行转账截图</p> <div class="photo"> <input type="file" id="upload_filePassport" ref="filePassport" class="upload__input" @change="uploadChangePassport" accept="image/*"> <div class="passport"></div> <div @click="upload_filePassport" class="imgUploadDiv"> <img :src="imgiDPassportUrl" alt=""> </div> </div> </div> </group> <div class="btn-login"> <flexbox> <flexbox-item> <x-button type="primary" @click.native="submitOtherInfor" :disabled="nextDisabled">提交</x-button> </flexbox-item> </flexbox> </div> </div> </div> </template> <script src="http://www.jq22.com/jquery/vue.min.js"></script> <script> import { XHeader, XInput, Group, XButton, Cell, Checker, CheckerItem, Datetime, Flexbox, FlexboxItem } from "vux" let time = null; export default { inject: ['reload'], components: { XHeader, XInput, XButton, Group, Cell, Checker, CheckerItem, Datetime, Flexbox, FlexboxItem }, data () { return { caseNo: '', imgName: '../../assets/img/customer/id_icon_add@2x.png', imgiDPassportUrl: '', imgList: [], imgFile: '', nextDisabled: false } }, mounted () { this.caseNo = this.$route.query.caseNo; this.getOtherInfor() }, methods: { goBack () { this.$router.go(-1) }, fileClick () { document.getElementById('upload_file').click() }, //选择图片 upload_filePassport () { clearTimeout(time); //首先清除计时器 time = setTimeout(() => { document.getElementById('upload_filePassport').click() }, 250) }, //获取图片 uploadChangePassport (e) { // 1. 先执行阻止操作 e.stopPropagation(); // 阻止冒泡 e.preventDefault(); // 阻止默认行为 // 2. 正确检测并打印状态(用事件属性,而非方法返回值) console.log('事件冒泡是否被阻止:', e.cancelBubble); // 标准浏览器输出 true console.log('默认行为是否被阻止:', e.defaultPrevented); // 标准浏览器输出 true // 3. 原有业务逻辑 this.uploadChange(e, 'imgiDPassport'); }, checkInfor () { if (this.imgList.imgiDPassport === undefined || this.imgList.imgiDPassport === "") { this.alert.methods.showModuleAuto('请上传付款证明') return false } return true }, loadImg (data) { let that = this if (data) { that.imageToBlob(data, function (blob) { console.log('url 转 blob'); console.log(blob); //付款证明 that.imgList.imgiDPassport = blob; }); } that.imgiDPassportUrl = data }, // image转Blob imageToBlob (src, cb) { let that = this; that.imageToCanvas(src, function (canvas) { cb(that.dataURLToBlob(that.canvasToDataURL(canvas))); }); }, imageToCanvas (src, cb) { var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = src; img.onload = function () { canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); console.log('canvas', canvas) cb(canvas); }; }, dataURLToBlob (dataurl) { console.log('dataurl', dataurl) var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]; var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }, canvasToDataURL (canvas, format, quality) { return canvas.toDataURL(format || 'image/jpeg', quality || 1.0); }, getOtherInfor () { this.bus.$emit('loading', true); this.$http.post(this.ApiUrl + '/confirmInsure/getPaymentProof', { caseNo: this.caseNo, }, { emulateJSON: true }).then(function (res) { this.bus.$emit('loading', false); if (res.data.code !== 0) { this.alert.methods.showModuleAuto(res.data.message) } else { console.log(res.data); if (res.data.data !== null) { console.log(res.data) if (res.data.data) { this.loadImg(res.data.data); } } } }, function (response) { this.bus.$emit('loading', false); console.log('请求失败啦'); }) }, submitOtherInfor () { if (this.checkInfor()) { let formData = new FormData(); formData.append("caseNo", this.caseNo) formData.append("proofFile", this.imgList.imgiDPassport, "proofFile.jpg"); this.bus.$emit('loading', true); this.nextDisabled = true this.$http.post(this.ApiUrl + '/confirmInsure/savePaymentProof', formData, { emulateJSON: true }).then(function (res) { this.bus.$emit('loading', false); if (res.data.code !== 0) { this.alert.methods.showModuleAuto(res.data.message) this.nextDisabled = false } else { let params = this.$encodeQuery(`${this.caseNo}`) this.$router.push(`/renewalDetail/${params}`); } }, function (response) { this.bus.$emit('loading', false); this.nextDisabled = false console.log('请求失败啦'); }) } }, //获取图片 uploadChange (e, imgType) { var that = this; let file = e.target.files[0]; if (file.size == 0) { return; } this.imgFile = file if (!/image\/\w+/.test(file.type)) { this.alert.methods.showModuleAuto("请选择图片"); return false; } var quality; if (file.size / 1024 < 512) { quality = 1 } else if (512 < file.size / 1024 < 1024) { quality = 0.5 } else if (1024 < file.size / 1024 < 3000) { quality = 0.2 } else if (3000 < file.size / 1024 < 5000) { quality = 0.1 } else if (5000 < file.size / 1024 < 10000) { quality = 0.06 } else if (10000 < file.size / 1024 < 20000) { quality = 0.03 } else { quality = 0.01 } this.compress(file, quality, function (base64Codes) { that.imgList.imgiDPassport = that.dataURLtoFile(base64Codes) }, imgType); console.log('that.imgList.imgiDPassport1', that.imgList.imgiDPassport) // 延迟100ms清空,避免浏览器重绘异常 setTimeout(() => { that.$refs.filePassport.value = null; }, 100); console.log('that.imgList.imgiDPassport2', that.imgList.imgiDPassport) }, canvasDataURL (path, q, fn, file) { var that = this; let img = new Image(); img.src = path; img.onload = function () { let that = this; console.log('that', that) let w = that.width, h = that.height, scale = w / h; w = 800; h = (w / scale); let quality = 0.8; //生成canvas let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); let anw = document.createAttribute("width"); anw.nodeValue = w; let anh = document.createAttribute("height"); anh.nodeValue = h; canvas.setAttributeNode(anw); canvas.setAttributeNode(anh); try { // 定义支持的MIME类型 const supportedMimeTypes = [ 'image/png', 'image/jpeg', 'image/gif', ]; const mimeType = supportedMimeTypes.find(type => type === file.type) || 'image/jpeg'; ctx.drawImage(that, 0, 0, w, h); quality = q; console.log('mimeType', mimeType); let base64 = canvas.toDataURL(mimeType, quality); fn(base64); } catch (e) { fn(path) } } }, compress (file, q, fn, imgType) { let ready = new FileReader(); ready.readAsDataURL(file); let that = this // 新增:捕获FileReader读取失败 ready.onerror = function (e) { console.error('FileReader读取异常:', e); that.alert.methods.showModuleAuto("图片读取失败"); }; ready.onload = function () { try { console.log('ready.onload', ready) let result = this.result; file.src = this.result // //尝试检测鸿蒙系统 // const isHarmonyOS = /harmonyos|arkweb/.test(navigator.userAgent.toLowerCase()); // if (isHarmonyOS) { // console.log('鸿蒙系统',navigator.userAgent); // // 鸿蒙系统下简化处理,不使用canvas压缩 // that.imgiDPassportUrl = result; // fn(result); // } else { // 其他系统使用原有处理 that.imgiDPassportUrl = result; console.log('that.imgiDPassportUrl', that.imgiDPassportUrl) that.canvasDataURL(result, q, fn, file); // } } catch (error) { console.error('图片压缩异常:', error); that.alert.methods.showModuleAuto("图片处理失败,请重新选择"); that.$refs.filePassport.value = null; } } // ready.readAsDataURL(file) }, dataURLtoFile (dataurl, filename) { //将base64转换为文件 let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); } } } </script>查看代码,并讲解
最新发布
09-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值