当你试图在jQuery中选择一个元素并且你知道只有一个元素时,出于性能原因使用first()
方法是否仍然有益,或者不是使用它?
例如:
$('#myForm').children('input[name=some_field]');
VS
$('#myElement').children('input[name=some_field]').first();
答案 0 :(得分:2)
不,不是"有益的" ... protected void ValidateUser(object sender, AuthenticateEventArgs e)
{
int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Seller_Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", Login1.UserName);
cmd.Parameters.AddWithValue("@Password", Login1.Password);
cmd.Connection = con;
con.Open();
userId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "Username and/or password is incorrect.";
break;
case -2:
Login1.FailureText = "Account has not been activated.";
break;
default:
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet);
break;
}
}
}
方法仅适用于DOM数组元素。
答案 1 :(得分:1)
{<1}}选择器可能会更好地短路搜索
:first
答案 2 :(得分:0)
在这种情况下,在jquery中使用.length
if($('#myForm').children('input[name=some_field]').length)
答案 3 :(得分:0)
如果它只是其中之一并且您知道id,请使用id。否则输入
// Get the value from a dropdown select
$( "select.foo option:selected").val();
// Get the value from a dropdown select even easier
$( "select.foo" ).val();
// Get the value from a checked checkbox
$( "input:checkbox:checked" ).val();
// Get the value from a set of radio buttons
$( "input:radio[name=bar]:checked" ).val();
即使您不想要这些值,也可以通过这种方式访问这些元素。只是几个直接访问它而不是从父元素访问它的例子。