简体   繁体   中英

jQuery Toggle div and class

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 Code:

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

jQuery Code:

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

The above code works to show/hide the div , but how can I add/remove class to show plus/minus sign when it is toggled ?

Initially, plus sign will be shown and div will be hidde. When clicked on it, minus sign will be shown and div will be displayed.

You need to use .toggleClass() with clicked elements context, you can pass the object in onclick method:

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>

You need to pass the current element as a param to the click handler and then toggle the class

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

then

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

I would recommend using jQuery event handlers instead of using inline handlers

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

then

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

It looks like jQuery also not works for show/hide div. Your code should be as below:

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM