-1

Say I have a unordered list of item1, item2, item3, item4, each with a div around it.

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

I want that every time I click itemX, it loads itemX.html and give the div around itemX a current class attribute. Currently I'm writing 4 functions separately for four items, and they look almost the same. So how can I write a general function that just works on any itemX, loads itemX.html and changes its div's attribute? My current code seems so redundant.

4

4 回答 4

2

假设您已经解决了 HTML 问题(li 应该是 ul 的子元素)。但仍然对于这样的问题,你需要这样做:

$("li").click(function() {
    $(".current").removeClass("current");
    $(this).parent().addClass("current");
});

但正确的解决方案是:

HTML:

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

JS:

$("li").click(function() {
    $(".current").removeClass("current");
    $(this).addClass("current");
});

并添加一些 CSS 到你的li

于 2013-05-18T22:14:53.780 回答
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 回答
0

您的问题不清楚,并且您的 html 无效。所以让我冒险猜测一下你想做什么。

<ul class="pages"><li>item</li><li>item2</li><li>item3</li></ul>
$(function(){
    $('ul.pages li').click(function(){
        // load html - not user what you mean, so how ever your doing your page load.
          $(this).addClass('someclass');
    });
});

这就是你要找的东西吗?

于 2013-05-18T22:14:52.460 回答