我正在尝试使用jQuery选择中找到的每个对象调用一个函数
<a href="#" class="can-click" data-code="a">a</a>
<a href="#" class="can-click" data-code="b">b</a>
<a href="#" class="can-click" data-code="c">c</a>
<a href="#" class="can-click" data-code="d">d</a>
每个a
元素都有一个数据代码值:
<p class="output" data-value="1"></p>
<p class="output" data-value="2"></p>
<p class="output" data-value="3"></p>
每个p
元素都有一个数据值:
$(document).ready(function () {
$(".can-click").click(function () {
var code = $(this).data("code");
$("output").each(Display(code));
});
});
我想要的是当你点击锚点a
时,你会收到一条警告,显示点击锚点的数据代码和每个p
的数据值,以及代码我想要弹出3个警报。
function Display(code) {
var p = $(this);
var value = p.data("value");
alert(code + " " + value);
}
以下是jsfiddle中代码的链接:http://jsfiddle.net/mikeu/XFd4n/
答案 0 :(得分:6)
您必须使用.
作为类选择器,并在调用this
函数时传递Display
对象,
$(document).ready(function() {
$(".can-click").click(function(e) {
e.preventDefault();
var code = $(this).data("code");
$(".output").each(function() { // use . for class selectors
Display(code, this); // pass this from here
});
});
});
function Display(code, ths) { // ths = this, current output element
var p = $(ths), // use ths instead of this
value = p.data("value");
console.log(code + " " + value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="can-click" data-code="a">a</a>
<a href="#" class="can-click" data-code="b">b</a>
<a href="#" class="can-click" data-code="c">c</a>
<a href="#" class="can-click" data-code="d">d</a>
<p class="output" data-value="1"></p>
<p class="output" data-value="2"></p>
<p class="output" data-value="3"></p>
答案 1 :(得分:4)
试试这个: -
您需要将函数引用传递给obj.each回调。 obj.each(Display(code))
错了,它应该是obj.each(Display)
;但是因为在这里你要传递变量,你可以在一个匿名函数中调用它。
$(".output").each(function(){
Display(code, this)});
});
$(document).ready(function () {
$(".can-click").click(function () {
var code = $(this).data("code");
$(".output").each(function(){
Display(code, this)});
});
});
function Display(code,$this) {
var p = $($this);
var value = p.data("value");
alert(code + " " + value);
}