2016-08-20 43 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>