-1

item1item2item3、の順序付けられていないリストがありitem4、それぞれがdiv前後にあるとします。

<ul>
  <div><li>item1</li></div>
  <div class="current"><li>item2</li></div>
  <div><li>item3</li></div>
  <div><li>item4</li></div>
</ul>

itemX をクリックするたびに、itemX.html が読み込まれ、itemX の周りの div に現在のクラス属性が与えられます。現在、私は4つの項目に対して4つの関数を別々に書いていますが、それらはほとんど同じに見えます. では、任意の itemX で機能し、itemX.html をロードし、その div の属性を変更する一般的な関数を作成するにはどうすればよいでしょうか? 私の現在のコードは冗長に思えます。

4

4 に答える 4

1

HTML が無効であるため、引き続き問題が発生します。LI 要素に css パディングを追加して、クリック領域を増やしてみてください。

<style>
    li { padding:10px; }
</style>

あなたの質問について:

<ul id="targetElement">
    <li data-contentName="item1.html">item one</li>
    <li data-contentName="item2.html">item two</li>
    <li data-contentName="item3.html">item three</li>
    <li data-contentName="item4.html">item four</li>
</ul>

<script type="text/javascript">
    $('#targetElement li').click(function(){  //for all li elements in #targetElement, do this on click
        //remove the active class from the other li's
        $('#targetElement li').removeClass('current');

        //jQuery wrap the current li 
        var $this = $(this);
        //add the class to the current li (the one that was clicked)
        $this.addClass('current');
        //get the name of the file to load
        var fileToLoad = $this.data('contentName');
        //then go about loading the file...
    });
</script>
于 2013-05-18T22:21:14.957 に答える
0
$("div li").on('click',function(){
  $(this).siblings().removeClass("current");
  $(this).load($(this).text() + ".html").closest("div").addClass("current");
});
于 2013-05-18T22:05:24.267 に答える