0

我有一个表格是这样的:

<form id="form1">
   <div id="teste1">
       aaa: <input id="aaa" name="aaa" type="text" />
       bbb: <input id="bbb" name="aaa" type="text" />
       ccc: <input id="ccc" name="aaa" type="text" />
   </div>
   <div id="teste2">
       ddd: <input id="ddd" name="aaa" type="text" />
   </div>
</form>

因此,在 jquery 中,我将 'form1' 元素放入变量中并将其传递给函数参数:

$.function({
   var temp = $("#form1");
   foo(temp);
});

然后,函数 foo 在其他脚本中,例如,我需要找到 id 'ddd'。我该怎么做?

foo = function(dataform)
{
   dataform.$("#ddd").val() ?????
};

多谢。

4

3 回答 3

0

Firstly, $.function is not part of the jQuery API and will be undefined. I suspect you want to use the ready event which is typically done like this:

$(document).ready(function ({
    var temp = $("#form1");
    foo(temp);
});

Secondly, $.$ is also not part of the jQuery API and so dataform.$("#ddd") will be also undefined. Since you're trying to find a descendant element (and not a direct child element), I would recommend the find method:

foo = function(dataform) {
   dataform.find("#ddd").val() //?????
};

Also, as an aside, in the above code you are not doing anything with the value of #ddd so there won't be any discernible actions visible on the page when it successfully executes.

Finally, assuming your markup is valid and each id attribute is unique, using .find to find an element by id is less efficient than simply searching by id (i.e., $('#ddd').val()). Mind you, this obviously defeats the purpose of passing $("#form1") as a function parameter but it's more efficient (in terms of querying the DOM) and it makes me wonder what you are trying to accomplish. If you can update your question with the overall goal, we may be able to better assist you.

于 2013-06-09T04:48:18.587 回答
0

你有没有尝试过element.find();element.children();

样本:

foo = function(dataform, inside)
{
   var element_you_want = dataform.children(inside);
};


foo($("#form1"), "#ddd");
于 2013-06-09T04:07:00.837 回答
0

工作 jsFiddle 演示

无需定义许多功能。向您的页面添加一个按钮:

<input type="button" id="check" value="Check Values" />

并将事件(例如click)附加到它:

$('#check').on('click', function () {
    // do stuff
});

现在,您可以获取其他元素并检查它们的值。您还需要等待文档准备好(以确保您的元素已加载到浏览器中):

$(function () {
    $('#check').on('click', function () {
        var ddd = $('#ddd').val();

        alert(ddd);
    });     
});
于 2013-06-10T02:48:02.023 回答