jQuery中的id操作



假设我有一个item1, item2, item3, 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个函数,它们看起来几乎相同。那么,我如何编写一个通用函数,只工作在任何itemX,加载itemX.html和改变其div的属性?我现在的代码看起来很冗余。

假设您已经修复了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");
});
li添加一些css

您的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>
$("div li").on('click',function(){
  $(this).siblings().removeClass("current");
  $(this).load($(this).text() + ".html").closest("div").addClass("current");
});

你的问题不清楚,你的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');
    });
});

这是你要找的吗?

最新更新