1

サイトのどのページを表示しているかに応じて開くナビゲーションバーを作成しています(PHPによって生成された「選択された」クラス)

jQueryでメソッドを作成し、それを特定のオブジェクトのIDにアタッチしようとしています。私はそれを可能な限りモジュール化したいと思います—そして私はjavascriptのOOPについてもう少し学ぼうとしています。

これが私のHTMLです:

<div id="workNav">Work</a></div>
<div  id="workNavContents">
  <a class="selected" href="foo.html">Video/Film</a>
  <a class="" href="foo.html">Photography</a>
</div>
<div id="clientsNav"><a href="#">Clients</a></div>
<div id="clientsNavContents">
  <a href="foo.html">Agencies/Clients</a>
  <a href="foo.html">Directors/Photographers</a>
</div>

そして私のJavascript:

var showSelected = new function(){
    if ($(this).children('.selected')){
        $(this).show();
    }
}

$('#workNavContents').showSelected = showSelected; 
$('#workNavContents').showSelected();

$('#clientNavContents').showSelected = showSelected; 
$('#clientNavContents').showSelected();

何かが私にjQuery対javascriptの重要なポイントをひどく見逃していることを教えてくれます。どんな助けでも大歓迎です。

ありがとう!M

4

2 に答える 2

2

$(...)呼び出すたびに新しいオブジェクトを返します。

代わりに、jQueryのプロトタイプにメソッドを追加する必要があります。

$.fn.showSelected = function() { ... };

その後、すべてのjQueryオブジェクトからアクセスできるようになります。

于 2013-03-07T01:41:01.127 に答える
0

Definitely missing a little bit of understanding. jQuery makes it easy to allow customization from the user. All you need to do is access jQuery's prototype which they expose through $.fn. Once this is in place, your extension may be used.

Note that I chose fade so that it was obvious that it worked

var showSelected = function(){
  if ($(this).children('.selected')){
    $(this).hide().fadeIn(2000);
  }
}
$.fn.showSelected = showSelected;//you could also simply assign the function to this
$('#workNavContents').showSelected();

Here is a demo: http://jsfiddle.net/mEgsX/

Also note that you do not need to use new on the function. That creates a function object and is a whole other conversation.

于 2013-03-07T01:45:25.133 に答える