1

リスト:

<ul class="div_chart1" data-quickcode="mac" data-questionid="1" >
    <li>
       <img src="inmark/pie_icon.jpg" class="pie_icon" onclick="ok()"/>
    </li>
</ul>

関数:

function ok(){          
    console.log($(this).parent().parent().data('quickcode'));
    console.log($(this).parent().parent().data('questionid'));  
}

関数 ok() は undefined を返します。これの何が問題なのですか?

4

2 に答える 2

6

this参照を引数としてインライン ハンドラに渡してみてください。

HTML:

<img src="inmark/pie_icon.jpg" class="pie_icon" onclick="ok(this)"/>

JS:

function ok(elem){          
    console.log($(elem).closest('ul').data('quickcode'));
    console.log($(elem).closest('ul').data('questionid'));  
}

デモ


そして、これを行う最良の方法は、

$('.pie_icon').click(function(e){
  e.stopPropagation();
  var parent = $(this).closest('ul');
  console.log(parent.data('quickcode'));
  console.log(parent.data('questionid'));  
});
于 2014-07-15T08:43:32.000 に答える
1

thisあなたの文脈では、グローバルウィンドウオブジェクトを参照しています。

console.log(this); // Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

要素オブジェクトを次のように渡します。

<img src="inmark/pie_icon.jpg" class="pie_icon" onclick="ok(this)"/>  


function ok(element) {
    console.log($(element).parent().parent().data('quickcode'));
    console.log($(element).parent().parent().data('questionid'));
} // here is element is HTML element object. Just wrap it with jQuery to use jQuery function.

インライン イベント ハンドラの詳細

于 2014-07-15T08:47:49.353 に答える