以下代码无效。我想将“this”(可能是.dot)从click事件传递给函数findTargetSlideOfDot
,但我不知道如何去做。感谢
$(document).on('click', '.dot', function() {
var targetSlide = findTargetSlideOfDot;
changeSlide(targetSlide);
})
function findTargetSlideOfDot() {
// find the slide number the user wants to see
var get = $.grep(this.className.split(" "), function(v, i){
return v.indexOf('slide_') === 0;
}).join();
var targetSlide = '.' + get;
return targetSlide;
}
function changeSlide(targetSlide) {
// hide current slide and dot
$('.slide.active, .dot.active').removeClass('active');
$(targetSlide).addClass('active');
}
答案 0 :(得分:0)
您可能希望将其作为参数传递给实际的调用该函数。并且应该应用Colton所显示的改进:
$(document).on('click', '.dot', function(e) {
var targetSlide = findTargetSlideOfDot( e.target );
changeSlide(targetSlide);
})
function findTargetSlideOfDot( element ) {
// find the slide number the user wants to see
var get = $.grep(element.className.split(" "), function(v, i){
return v.indexOf('slide_') === 0;
}).join();
var targetSlide = '.' + get;
return targetSlide;
}
function changeSlide(targetSlide) {
// hide current slide and dot
$('.slide.active, .dot.active').removeClass('active');
$(targetSlide).addClass('active');
}
答案 1 :(得分:0)
下面:
$(document).on('click', '.dot', function() {
var targetSlide = $(this);
changeSlide(targetSlide);
})
function changeSlide(targetSlide) {
// hide current slide and dot
//$('.slide.active, .dot.active').removeClass('active');
$(targetSlide).toggleClass('active');
}
.dot{
width: 100px; border: 1px solid black;
padding: 10px; margin: 5px;
}
.dot.active{
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dot">test</div>
答案 2 :(得分:0)
给这一点,修改你的点击功能:
$(document).on('click', '.dot', function(e) {
// e.target should refer to the element with the dot class
})
这也是一个功能代码笔:http://codepen.io/csavage1994/pen/Mppxaa
答案 3 :(得分:0)
您可以选择:
$(document).on('click', '.dot', function(e) {
findTargetSlideOfDot(e.target);
});
它为您提供触发事件的元素(被点击)
和
$(document).on('click', '.dot', function(e) {
findTargetSlideOfDot(e.currentTarget);
});
,它为您提供了已注册事件侦听器的元素。