2016-06-28 9 views
0

jsファイルの別の関数にあるhtmlファイルから関数をトリガーしようとしています。 triggerメソッドを使用しようとしていますが、動作させることができません。 これを行う方法は何ですか? FIDDLEjQuery - 関数をトリガーする

<div id="result4" style="color:white; background:black"> 
    from function 
</div> 


<script> 
    var TEST = new test({ 
    type: "image", 
    file: "test.jpg", 
    breakingPoint: 100 
    }); 

    TEST.trigger('reset'); 

</script> 

JS

function test(args) { 

    $this.on('reset', function() { 
    $("#result4").html("new text"); 
    console.log("OK"); 
    }); 

} 
+1

あなたの 'TEST'オブジェクトには' trigger'メソッドがあると思いますか?また、あなたのコードに '$ this'変数を定義しません。あなたのコードには、あなたが何をしようとしているかを知らずに誰もあなたを助けることができないいくつかの問題があります。 – undefined

+0

@JeremyJStarcher私は 'TypeError:TEST.triggerは関数ではありません。 ( 'TEST.trigger(' reset ')'、 'TEST.trigger'は定義されていません) ' – SNos

+0

@Vohumanそれがない場合、どのようにしてトリガーメソッドを追加してテストできますか? – SNos

答えて

-1

あなたはjquerys readyイベント内のコードにタグを付け包みます。これは、DOMが読み込まれた後ではなく、解析されたときに実行されます。

はたぶん、これはあなたが探しているものです:

$this.on('reset', function() { 
    $("#result4").html("new text"); 
    console.log("OK"); 
}); 

<script> 
$(document).ready(function(){ 
    var TEST = test({ 
     type: "image", 
     file: "test.jpg", 
     breakingPoint: 100 
    }); 

    TEST.reset(); 
}); 
</script> 

JSファイル

var test = function(options){ 
    var that = {}; 
    // you can use type, file & breaking point with option.type options.file etc.. 
    that.reset = function() { 
     $("#result4").html("new text"); 
     console.log("OK"); 
    }; 

    return that; 
}; 
+0

'$(document).ready'はあらゆる問題を解決できる魔法ではありません。 – undefined

+0

ありがとうございます。私はまだ '' TEST.trigger 'が定義されていません。 – SNos

0

でコンソールログを見ると、あなたのフィドルは、エラーが発生しました$thisは定義されていません。

とトリガーのドキュメントを見て:あなたは間違ってそれを呼び出している

​​

triggerメソッドを持たない独自のオブジェクトを作成しています。

0

トリガーはjquery関数でありネイティブJavaScript Object関数ではないため、$ thisを定義してテスト用オブジェクトとして返す必要があります。

function test(args) { 
     var $this = $(this); // declare $this 
    var default_options = { 
    breakingPoint: 2000 
    }; 

    var options = $.extend({}, default_options, args); 

    $("#result1").html(options.type); 
    $("#result2").html(options.file); 
    $("#result3").html(options.breakingPoint); 

    $this.on('reset', function() { 
    $("#result4").html("new text"); 
    console.log("OK"); 
    }); 
    return $this; 

} 

var TEST = new test({ 
    type: "image", 
    file: "test.jpg", 
    breakingPoint: 100 
}); 

TEST.trigger('reset'); 
+0

ありがとうございます。私は戻りませんでした。 – SNos

+0

@SNos np。しかし、あなたはまた、var $ this = $(これ)を見逃していました。 – Hoyen

+0

はい、フィドルで私はそれを忘れました – SNos

関連する問題