2011-11-10 3 views
0

jQueryの新機能です。私は関数に値を渡そうとしています。jQuery "this" issue

<div class="the_service" id="ecommerce" onClick="javascript: gorightthere(ecommerce);"> 

function gorightthere(this){ 

    var gothere = $('h2[name="'+this+'"]'); 
    if (gothere.length){ 
$('html, body').animate({ 
        scrollTop: gothere.offset().top 
        }, 2000); 
     removeClass('selected'); 
     gothere.addClass('selected'); 
    } 
}; 

私がしようとしているのは、 "eコマース"という値を関数に渡すことです。私は渡すべき多くの異なる値を持っているので "this"を使用したいと思います。そして、私はonClickイベントの後に渡すすべての値で動作する関数を実行したいと思います。

助けが必要ですか?

おかげ

+0

jsの前に 'javascript:'を入れる必要はありません – mrtsherman

答えて

7

はあなたの変数名は予約キーワードthisと競合しています。別の変数名を使用すると、すべて設定する必要があります。

function gorightthere(value) {  
    var gothere = $('h2[name="' + value + '"]'); 
    if (gothere.length){ 
     $('html, body').animate({ 
      scrollTop: gothere.offset().top 
      }, 2000); 
     removeClass('selected'); 
     gothere.addClass('selected'); 
    } 
}; 
1

よりもむしろ「この」を使用して、なぜ同じように、通常の変数を使用しない:一般的に、あなたはそれがほぼすべてのCベースの言語では非常に特定の意味を持っているので、変数名にthisを使用しないでくださいパラメータ?これは、thisがJSのキーワードであるためです。

1

「これは」です予約キーワード、このコードを試してみてください。実際に

<div class="the_service" id="ecommerce" onClick="javascript: gorightthere(this);"> 

function gorightthere(element){ 

    var gothere = $(element); 
    if (gothere.length){ 
$('html, body').animate({ 
        scrollTop: gothere.offset().top 
        }, 2000); 
     removeClass('selected'); 
     gothere.addClass('selected'); 
    } 
}; 
0

あなただけそうのようなあなたの変数を逆転できる:あなたのdivタグの変更で - >ジャバスクリプト:gorightthere(これを)。 関数gorightthere(eコマース){

var gothere = $('h2[name="'+ecommerce.id+'"]'); 

は、そうでなければ他のわずかな変更が必要とされ、あなたのH2要素に名前を表すために、あなたのdivであなたのIDを仮定。