能否请您看一下这段代码,让我如何在dom事件内部的外部函数中绑定$(this)
?
$(".adder").on("click", function(){
updateText();
});
function updateText(){
$(this).next(".mapper").html("Got You!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default adder">Left</button>
<button type="button" class="btn btn-default mapper">Middle</button>
<button type="button" class="btn btn-default">Right</button>
</div>
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default adder">Left</button>
<button type="button" class="btn btn-default mapper">Middle</button>
<button type="button" class="btn btn-default">Right</button>
</div>
</div>
答案 0 :(得分:3)
您应该能够将此作为参数传递:
$(".adder").on("click", function(){
var node = $(this);
updateText(node);
});
function updateText(node){
node.next(".mapper").html("Got You!");
}
答案 1 :(得分:2)
执行此操作的一种方法如下:
function updateText(){
$(this).next(".mapper").html("Got You!");
}
$(".adder").on("click", updateText);
另一个是
function updateText(){
$(this).next(".mapper").html("Got You!");
}
$(".adder").on("click", function(){
updateText.bind(this)();
});
答案 2 :(得分:0)
function updateText(e){
e.next(".mapper").html("Got You!");
}
$(".adder").on("click", function(){
updateText($(this));
});