zoukankan      html  css  js  c++  java
  • 行间事件传this的问题:

    在做1个简单功能的时候,行间事件这块发现了1个问题:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    </head>
    
    <body>
    <a onclick="fn()">a标签</a>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
    	function fn(obj){
    	var t = $(this).text();
    	console.log("t:"+t);
    	}
    </script>
    </body>
    </html>
    

      

    打印不出来t。事实上,这样做获取不到元素,也就是说$(this)为空。很奇怪了,这种写法也经常见:

     1 <!doctype html>
     2 <html>
     3 <head>
     4 <meta charset="utf-8">
     5 <title>无标题文档</title>
     6 </head>
     7 
     8 <body>
     9 <a>a标签</a>
    10 <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
    11 <script>
    12 $('a').click(function(){
    13     var t = $(this).text();
    14     console.log(t);
    15     alert(t);
    16     })
    17     
    18 </script>
    19 </body>
    20 </html>

    事实上,这种写法就能获取的到。

    那行间事件怎么传this呢?如下:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    </head>
    
    <body>
    <a onclick="fn(this)">a标签</a>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
        function fn(obj){
        var t = $(obj).text();
        console.log(t);
        alert(t);}
    </script>
    </body>
    </html>

    注意,函数的形参不能直接写this,因为this是一个关键字$(obj)的作用是将原生的dom对象转换成jquery对象这样可以很方便的进行操作了。

    总结:第1种写法有问题,其他两种都可以。有时候事件写在行间方便点,因为动态语言生成页面的时候,传值很方便,除了this,我们还可以传后台的数据,jsp中比如:

    <a onclick="createChild(${map2.id},${map2.parentid},'${map2.url}','${map1.menuname}')" >(修改)</a>。

    这时候要在JavaScript要用到this,那么这样即可:

    1 <a  onclick="createChild(${map2.id},${map2.parentid},'${map2.url}','${map1.menuname}',this)" >(修改)</a>

    不用this的时候把事件写在外面,本文中第二种写法。

  • 相关阅读:
    python相关的报错处理
    各版本数据库初次登录时,强制修改密码
    机器被感染病毒文件zigw的处理流程
    Let's encrypt申请泛域名证书以及报错处理
    添加/修改保存
    request.getRemoteUser() Spring Security做权限控制后
    hibernate hbm.xml配置映射
    hibernate 注解配置<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/X
    Web.xml配置详解之context-param
    在web.xml中通过contextConfigLocation配置spring
  • 原文地址:https://www.cnblogs.com/xiaochongchong/p/5446323.html
Copyright © 2011-2022 走看看