草庐IT

小结event.target与this

wyl-1113 2023-03-28 原文
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        .box1 {
            width: 200px;
            height: 200px;
            background-color: black;
        }

        .box2 {
            width: 100px;
            height: 100px;
            background-color: red;
        }

        .box3 {
            width: 50px;
            height: 50px;
            background-color: blue;
        }
    </style>
    <script type="text/javascript">
         //案例中点击box3时:分别会出现以下情况
        // 使用target会弹出三次box3
        // 使用this会弹出box3 box2 box1(冒泡)
        window.onload = function () {
            var box1 = document.getElementsByClassName("box1")[0];
            var box2 = document.getElementsByClassName("box2")[0];
            var box3 = document.getElementsByClassName("box3")[0];
            box1.onclick = function (event) {
                event = event || window.event;  //估计是兼容性写法
                alert(event.target.className);  //event.target指向的是被触发事件(被点击)的对象
                // alert(this.className);   //this指向的是事件绑定的对象
            }
            box2.onclick = function (event) {
                event = event || window.event;
                alert(event.target.className);
                // alert(this.className);
            }
            box3.onclick = function (event) {
                event = event || window.event;
                alert(event.target.className);
                // alert(this.className);
            }
        }

        // 运行这个DEMO,在事件冒泡的背景下,点击box3,event.target.className为box3,之后冒泡的事件弹出的信息也为box3;
        // 这是因为event.target指向的是被触发事件(被点击)的对象(box3),仅通过box3触发了一次事件(点击),所以只弹出一次box3;
        // 而this.name则依次弹出的为box3,box3,box1,这是因为this指向的是事件绑定的对象,事件冒泡中连续触发了三次事件,这三次事件绑定的对象都不同。
        // 简单的说就是,你点击了box3,那么e.target就是box3;并且由于你点击了box3,通过点击box3冒泡触发了box1,box2,
        // 在box1和box2的事件中,e.target也是box3。但是this是谁,就和由谁触发了事件无关了。比如,无论是box2,还是box3触发了box1的事件,还是box1的事件根本没有被触发,box1的事件的this永远都是box1,忠心耿耿


        // ========================总结==========================
        // 1.this是Javascript语言的一个关键字。

        // 2.this代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。

        // 3.event 对象代表事件的状态,比如事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状态。

        // 4.this和event.target的区别:

        // js中事件是会冒泡的,所以this是可以变化的,但event.target不会变化(在事件触发时,只传递当前event对象的引用),它永远是直接接受事件的目标DOM元素;

        // 另外,this和event.target都是dom对象,如果要使用jquey中的方法可以将他们转换为jquery对象:$(this)和$(event.target);

    </script>
</head>

<body>
    <div class="box1">
        <div class="box2">
            <div class="box3">

            </div>
        </div>
    </div>
</body>

</html>

有关小结event.target与this的更多相关文章

  1. ruby - 你会如何在 Ruby 中表达成语 "with this object, if it exists, do this"? - 2

    在Ruby(尤其是Rails)中,您经常需要检查某物是否存在,然后对其执行操作,例如:if@objects.any?puts"Wehavetheseobjects:"@objects.each{|o|puts"hello:#{o}"end这是最短的,一切都很好,但是如果你有@objects.some_association.something.hit_database.process而不是@objects呢?我将不得不在if表达式中重复两次,如果我不知道实现细节并且方法调用很昂贵怎么办?显而易见的选择是创建一个变量,然后测试它,然后处理它,但是你必须想出一个变量名(呃),它也会在内存中

  2. ruby-on-rails - Rails - Carrierwave 进程抛出 ArgumentError : no images in this image list - 2

    在尝试实现应用auto_orient的过程之后!对于我的图片,我收到此错误:ArgumentError(noimagesinthisimagelist):app/uploaders/image_uploader.rb:36:in`fix_exif_rotation'app/controllers/posts_controller.rb:12:in`create'Carrierwave在没有进程的情况下工作正常,但在添加进程后尝试上传图像时抛出错误。流程如下:process:fix_exif_rotationdeffix_exif_rotationmanipulate!do|image|

  3. ruby - :this means in Ruby on Rails? 是什么 - 2

    我是Ruby和RubyonRails世界的新手。我已经阅读了一些指南,但我在使用以下语法时遇到了一些麻烦。我认为在Ruby中使用:condition语法来定义具有某种访问器的类属性,例如:classSampleattr_accessor:conditionend隐式声明“条件”属性的getter和setter。当我查看一些Rails示例代码时,我发现以下示例我并不完全理解。例如:@post=Post.find(params[:id])为什么它使用这种语法访问id属性,而不是:@post=Post.find(params[id])或者,例如:@posts=Post.find(:all):

  4. ruby - 无法加载此类文件——脚本/rails : Getting this error while remote debugging through RubyMine - 2

    我在通过RubyMineIDE进行远程调试时遇到以下错误。$bundleexecrdebug-ide--port1234--script/railsserverFastDebugger(ruby-debug-ide0.4.9)listenson:1234/home/amit/.rvm/gems/ruby-1.9.3-p125/gems/ruby-debug-ide19-0.4.12/lib/ruby-debug-ide.rb:123:in`debug_load'/home/amit/.rvm/gems/ruby-1.9.3-p125/gems/ruby-debug-ide19-0.4.

  5. jquery - Rails 4 如何捕捉 ajax :success event - 2

    我正在使用Rails4.0。我正在发送这样的事件(注意:remote=>true):true,:class=>"rate-btnyes-btnbtnbtn-defaultbtn-sm"}%>我的Controller看起来像这样:defratevideo=Video.find_by(hashed_id:params[:id])action=params[:yesno]putsvideo.hashed_idputsactionrespond_todo|format|if(action=='yes')new_rating=video.rating==1?0:1video.update(is_

  6. ruby-on-rails - Rails 中的推杆 : "Unknown auth_key" - server side not triggering events - 2

    我正在尝试将Pusher插入到我已经很晚的Rails应用程序中。客户端工作正常-使用PusherEventCreator触发所需的javascript。但是服务器端不工作:在我的通知Controller中使用以下代码创建要测试的操作:Pusher.trigger('private-4','new_message',{:from=>"christian",:subject=>"hello"})给出这个错误:Pusher::AuthenticationError(Unknownauth_key):app/controllers/notifications_controller.rb:57:

  7. ruby-on-rails - rails 错误 method_missing':Gem::Specification 的未定义方法 `this' - 2

    我遵循这个教程:https://guides.spreecommerce.com/developer/getting_started_tutorial.html#installing-image-magick当我写作时jonstark@jonstark-pc:~/rails_projects/optima1$spreeinstall--auto-accept我明白了:/home/jonstark/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/specification.rb:2158:in`method_missing':undefine

  8. ruby - JRuby cannot switch to 1.6.2 for this interpreter error rvm - 2

    我正在尝试在UbuntuLinux上使用RVM配置JRuby。我已成功安装RVM,但在尝试安装Jruby时,出现以下错误:dlitwak@ubuntu:~$rvminstalljruby-1.6.0jruby-1.6.0-#fetchingjruby-1.6.0-#extractedto/home/dlitwak/.rvm/src/jruby-1.6.0(alreadyextracted)BuildingNailgunjruby-1.6.0-#installingto/home/dlitwak/.rvm/rubies/jruby-1.6.0**ERROR:Cannotswitchto1

  9. ruby-on-rails - 如何在 Rails 中更改 "3 errors prohibited this foobar from being saved"验证消息? - 2

    在我的Rails应用程序中,我在我的事件记录对象中使用了验证助手,它们非常棒。当出现问题时,我会在我的网页上看到标准的“3个错误禁止保存此foobar”以及个别问题。有什么方法可以用我自己的方式覆盖这个默认消息吗? 最佳答案 用于显示错误的error_messages_for助手接受一个:header_message选项,该选项允许您更改默认标题文本。如:error_messages_for'model',:header_message=>"Youhavesomeerrorsthatpreventedsavingthismodel"

  10. ruby-on-rails - Ruby BigDecimal 圆 : Is this an error? - 2

    在用一个表示为BigDecimal的值编写测试时,我遇到了一些奇怪的事情并决定深入研究它。简而言之,四舍五入到小数点后两位的“0.00009”返回为0.01而不是0.00。真的。这是我的脚本/控制台捕获:>>bp=BigDecimal('0.09')=>#>>bp.round(2,BigDecimal::ROUND_HALF_DOWN).to_f=>0.09>>bp=BigDecimal('0.009')=>#>>bp.round(2,BigDecimal::ROUND_HALF_DOWN).to_f=>0.01>>bp=BigDecimal('0.0009')=>#>>bp.roun

随机推荐