2011-07-29 70 views
1

我有以下形式。需要帮助选择一个jQuery选择

<form action="" method="post" id="save-user"> 
    <button type="button" name="save-user">Save</button> 
    <button type="button" name="save-user-close">Save & Close</button> 
    <input type="text" name="name" placeholder="Enter your name" required/> 
    <input type="email" name="email" placeholder="Enter your email" required/> 
</form> 

我是如何创建的所有输入和按钮元素jQuery选择,因为我没有使用一个id属性,我不想在这种情况下使用它混淆。我如何检索或创建所有四个表单元素的选择器。

谢谢。

回答

2

以上所有的答案都OK,但你可以,当然也最应该学习(学习)使用这种as pseudo classes, attribute selectors and more高级选择。
这里有你的情况下的几个例子:

// all the buttons that are children of the container 
//with the attribute id equal to "save-user" 
$("#save-user").find('button'); 

// all the buttons that have their name attribute starting with "save-user" 
$('button[name^=save-user]'); 

// same as before, only that we filter the results 
// by checking if they contain the text "Save" 
$('#save-user').find('button').filter(':contains(Save)'); 

你只能使用jQuery选择的创建更加复杂的查询 - withouth的一个ID或类绑定到元件的需要 - 适合您的需求。当然,主要的缺点是效率,但如果你不滥用的特殊选择,您的jQuery的编码风格可以说是相当凉爽。

1

怎么样...... $('#save-user button,#save-user input').blah();

1
$("#save-user").find("button, input") 
0

您可以使用$(':button[name="save-user"]')的按钮,$(':input[name="name"]')输入。