jQuery切换div和类

时间:2015-03-25 06:26:56

标签: javascript jquery html css

CSS:

.project_toggle_on {
    padding-right:20px;
    cursor:pointer;
    background: url(../images/minus.jpg) no-repeat;
}

.project_toggle_off {
    padding-right:20px;
    cursor:pointer;
    background: url(../images/plus.jpg) no-repeat;
}

HTML代码:

<span class="project_toggle_off" onclick="toggle_timesheet('10');"></span>
<div style="display: none;" id="task_10" class="task_project_id"></div>

jQuery代码:

function toggle_timesheet(task_id) {
    //$(this).toggleClass('project_toggle_off');
    $("#" + task_id).slideToggle(100);
}

以上代码用于显示/隐藏div,但如何在切换时添加/删除类以显示plus/minus符号?

最初,将显示加号,div将显示为hidde。单击它时,将显示减号,并显示div。

3 个答案:

答案 0 :(得分:0)

您需要对点击的元素上下文使用.toggleClass(),您可以在onclick方法中传递对象:

<强> JS:

function toggle_timesheet(task_id,obj) {
  $(obj).toggleClass('project_toggle_off');
  $("#" + task_id).slideToggle(100);
}

<强> HTML:

<span class="project_toggle_off" onclick="toggle_timesheet('10',this);"></span>
<div style="display: none;" id="task_10" class="task_project_id"></div>

答案 1 :(得分:0)

您需要将当前元素作为参数传递给click处理程序,然后切换类

<span class="project_toggle_off" onclick="toggle_timesheet('10', this);"></span>
<div style="display: none;" id="task_10" class="task_project_id"></div>

然后

function toggle_timesheet(task_id, el) {
    $(el).toggleClass('project_toggle_off project_toggle_on');
    $("#" + task_id).slideToggle(100);
}

我建议使用jQuery事件处理程序而不是使用内联处理程序

<span class="project_toggle project_toggle_off" data-task="10"></span>
<div style="display: none;" id="task_10" class="task_project_id"></div>

然后

$('.project_toggle').click(function () {
    var $this = $(this);
    $this.toggleClass('project_toggle_off project_toggle_on');
    $("#task_" + $this.data('task')).slideToggle(100);
})

答案 2 :(得分:0)

看起来jQuery也不适用于show / hide div。 您的代码应如下所示:

HTML:

<span class="project_toggle_on project_toggle_off" onclick="toggle_timesheet('10', this);"></span>
<div style="display: none;" id="task_10" class="task_project_id"></div>

的jQuery

function toggle_timesheet(task_id, toogleObj) {
 $("#task_" + task_id).slideToggle(100);
 $(toggleObj).toggleClass('project_toggle_off');
}