将其他参数传递给jQuery each()回调

编程入门 行业动态 更新时间:2024-10-28 08:25:28
本文介绍了将其他参数传递给jQuery each()回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在开发一款可向用户展示调查问题的应用。标记看起来像这样:

I'm working on an app that will present surveys to the user. The markup looks something like this:

<body> <div class="question" id="q1"> Question 1 </div> <div class="question" id="q2"> Question 2 </div> <!-- etc --> </body>

我想使用jQuery从DOM构造JavaScript对象,所以在 Survey 构造函数我正在使用 each()方法遍历jQuery集。问题是在回调函数中我无法获得对 Survey 对象的引用,以便附加每个问题对象 Survey.questions 数组。如何获得对 Survey 对象的引用?有没有办法将附加参数(例如对 Survey 对象的引用)传递给回调函数?

I want to construct the JavaScript objects from the DOM using jQuery, so in the Survey constructor I'm traversing the jQuery set using the each() method. The problem is that within the callback function I'm unable to get a reference to the Survey object in order to append each Question object to the Survey.questions array. How can get a reference to the Survey object? Is there a way to pass an additional parameter (e.g. a reference to the Survey object) to the callback function?

function Survey() { this.questions = new Array; $('.question').each(function(i) { (/* Survey object */).questions.push(new Question(this)); }); } function Question(element) { this.element = $(element); }

推荐答案

你应该能够创造在迭代问题之前参考您的调查。

You should be able to create a reference to your survey before you iterate over the questions.

function Survey() { this.questions = new Array(); var survey = this; $('.question').each(function(i) { survey.questions.push(new Question(this)); }); } function Question(element) { this.element = $(element); } var survey = new Survey(); $.each(survey.questions, function() { $("ul").append("<li>" + this.element.text() + "</li>"); });

jsfiddle

更多推荐

将其他参数传递给jQuery each()回调

本文发布于:2023-11-23 10:42:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621152.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   参数   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!