LoginSignup
2
0

More than 5 years have passed since last update.

javascipt(jQuery) $(this)の代入値について

Last updated at Posted at 2018-01-14

$(this)の値の移り変わりに関して

javascrpt(jQuery)でコールバックして式が長くなると$(this)値に入っているものが変わってきます。

<!DOCTYPE html>
<html lang="ja">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script src='https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js'></script>
<title>documentwrite</title>
</head>
<body>

<p id="panel1">パネル1</p>
<p id="panel2">パネル2</p>
<p id="panel3">パネル3</p>




<script src="/js/jquery-2.2.4.min.js"></script>
<script>

$(function(){
    $("p").on("click",function(e){
        let E = $(this);
        let D;
        $("#panel1,#panel2,#panel3").each(function(){
            if(e.target === $(this).context){
                D = $(this);
                $(this).text("ヒットしました。");
            }
        })
        console.log(E);
        console.log(D);
    })
});


</script>
</body>
</html>
    $("p").on("click",function(e){
        let E = $(this);
        let D;

このときの$(this)にはクリックされた"p"が代入されている。

        $("#panel1,#panel2,#panel3").each(function(){
            if(e.target === $(this).context){
                D = $(this);
                $(this).text("ヒットしました。");

このときの$(this)にはeach関数でそれぞれの("#panel1,#panel2,#panel3")を見ていっている状態です。
("#panel1")を見ているときはそれが$(this)になります。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0