私はこの単純な関数をいくつかのhtmlをコピーし、別のdivに配置します。 私は関数のコードをclickイベントに入れてもうまく動作しますが、複数の場所で使用する関数に移動すると機能しません。 これはなぜですか?
I console.log($(this));関数ではウィンドウ要素を返します。 http://codepen.io/ashconnolly/pen/ebe7a5a45f2c5bbe58734411b03e180e
私は別の方法で$(this)を参照する必要があります - ?ここcodepen
function addHTMLtoComponent() {
var wrapper = $(this).closest(".wrapper");
var component = $(wrapper).find(".component");
var componentCodeHolder = $(wrapper).find('.target');
$(componentCodeHolder).text(component.html())
//console.log($(this));
}
$(".js_show_html").click(function() {
addHTMLtoComponent();
});
あなたの関数に '' $(この)合格する必要があります'addHTMLtoComponent($(this)) 'で呼び出す – TAGraves
関数は呼び出し元が誰であるかを知らないので、' this'が誰を指しているのかわからないので、それをパラメータとして渡す必要があります – ochi
また、 'this'がなぜそれを行うのかについての詳細はhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/thisを見てください。 – TAGraves