2016-08-20 41 views
0

当我单击div内的图像时,它将切换其类,一次我不希望它完成,我只是希望它切换父级div的类。我怎样才能阻止它一起切换?类虽然被设置为删除,但切换一次

// .item 
 
function swap() { 
 
    $('#' + event.target.id).toggleClass('selected'); 
 

 
    } 
 
    // .boop 
 

 
function swapDad() { 
 
    var par = $('#' + event.target.id).parent().attr('id'); 
 
    $('#' + par).toggleClass('selected'); 
 
    $('#' + event.target.id).removeClass('selected'); 
 

 
}
#itemz { 
 
    border: solid 1px black; 
 
} 
 
.item { 
 
    margin: 5px; 
 
    border: white 3px solid; 
 
    background-color: grey; 
 
    width: 125px; 
 
    height: 150px; 
 
    text-align: center; 
 
    vertical-align: bottom; 
 
    display: inline-block; 
 
} 
 
.selected { 
 
    border: green 3px solid; 
 
} 
 
.boop { 
 
    width: 100px; 
 
    height: 100px; 
 
    display: block; 
 
    margin-left: auto; 
 
    margin-right: auto; 
 
    margin-top: 10px; 
 
    margin-bottom: 10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="itemz"> 
 
    <div class="item" id="1" onclick="swap()"> 
 
    <img src="http://placehold.it/100/000/fff?text=test" class="boop" onclick="swapDad()" id="img1">Something 
 
    </div> 
 
    <div class="item" id="2" onclick="swap()"> 
 
    <img src="http://placehold.it/100/000/fff?text=test2" class="boop" onclick="swapDad()" id="img2">Something 
 
    </div> 
 
</div>

+1

有做'$( “#” + event.target.id)'没有意义的。当变量中有元素时,不需要搜索ID,可以使用'$(event.target)'。另外,您需要将'event'参数添加到函数定义和函数调用中。 – Barmar

+1

你应该避免在html元素上使用'onlick'属性,使用正确的事件侦听器isntead – empiric

回答

0

当您单击图像,单击事件也传播到包含它的DIV,所以它调用swapDad()然后swap()。如果您只想切换DIV的类别,则img中不需要有onclick="swapDad()"

而不是使用全局变量event,这是非标准的,在所有浏览器中都不可用,您应该将该元素作为参数传递给该函数。

// .item 
 
function swap(div) { 
 
    $(div).toggleClass('selected'); 
 
}
#itemz { 
 
    border: solid 1px black; 
 
} 
 
.item { 
 
    margin: 5px; 
 
    border: white 3px solid; 
 
    background-color: grey; 
 
    width: 125px; 
 
    height: 150px; 
 
    text-align: center; 
 
    vertical-align: bottom; 
 
    display: inline-block; 
 
} 
 
.selected { 
 
    border: green 3px solid; 
 
} 
 
.boop { 
 
    width: 100px; 
 
    height: 100px; 
 
    display: block; 
 
    margin-left: auto; 
 
    margin-right: auto; 
 
    margin-top: 10px; 
 
    margin-bottom: 10px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="itemz"> 
 
    <div class="item" id="1" onclick="swap(this)"> 
 
    <img src="http://placehold.it/100/000/fff?text=test" class="boop" id="img1">Something 
 
    </div> 
 
    <div class="item" id="2" onclick="swap(this)"> 
 
    <img src="http://placehold.it/100/000/fff?text=test2" class="boop" id="img2">Something 
 
    </div> 
 
</div>