我不能让内容保持开放,当我点击自己。当我点击触发它的按钮时,当它在任何地方被点击时(这是正确的),它就会关闭。我以文档为目标,因为基于不同的标记元素,我将具有不同的功能。
当单击内容本身时,如何防止内容关闭?

Javascript
$( document ).on( "click", function( event ) {
// Add internal reference
$( ".target-2" ).addClass( "gStarter" );
$( ".content-col" ).addClass( "gColumn" );
// Check if the elem been clicked has target-2 as class
// and if the tag name matches a button tag
if( $(event.target).hasClass( "target-2" ) && $( event.target ).prop( 'tagName' ) == "BUTTON" ){
// Add active class if it doesn't have it
if( ! $( ".target-2" ).parent().next().children().hasClass( "active" ) ){
// Make sure there won't be any content activated
//$( ".gColumn" ).removeClass( "active" );
//$( ".gStarter" ).removeAttr( "data-starter" );
// Add active class
$( ".target-2" ).parent().next().children().addClass( "active" );
} else {
/*
* Already have active class
*/
// Hide content by removing the class
$( ".target-2" ).parent().next().children().removeClass( "active" );
// Remove data-starter attribute
$( ".target-2" ).removeAttr( "data-starter" );
}
} else {
// Find and get the first class by targeting its data-starter attribute
//var find = $('[data-starter="starter-active"]');
// var getClass = $(find).attr('class').toString().split(' ')[0];
if ( ! $( ".target-2" ).closest().parent().next().children().is( event.target )) {
if ( $( ".target-2" ).parent().next().children().is(':visible')) {
$( ".target-2" ).parent().next().children().removeClass( "active" );
}
}
}
});<div class="host">
<div class="btn-container">
<button type="button" data-starter="starter-active" class="target-2 target">Click here</button>
</div>
<div class="button-row row">
<div class="button-col content-col">
<span>This content is triggered by a button - ID: 13</span>
</div>
</div>
</div>发布于 2018-01-25 18:58:47
为什么不检查目标是否有特定的类名呢?
例如,将类名添加到
<div class="button-row row my-content" />然后检查$(event.target).hasClass(‘my’)。
此外,您还可以使用数据属性动态地实现它。
在单击此处按钮上添加一个数据属性。如下所示:
<div data-content-target="my-content">Click Here</div>然后,在javascript中,不是遍历DOM树(parent().next().children().addClass()),而是选择元素并添加活动类,如下所示:
var targetContent = $(".target-2").data("content-target");
$("." + targetContent).addClass("active");这是一种更好的方法,原因很多,但首先,它大大降低了代码的复杂性。
https://stackoverflow.com/questions/48449832
复制相似问题