我有以下html,我想在div中获取输入
var input1 = $("#div1 .myinput"); OR
var input1 = $("#div1").find(".myinput");
要获得输入,我有两种方法,问题是哪一种是首选。到目前为止,我尝试了以下两种方法。请建议哪一个更好以及为什么或者如果还有其他最好的方法来通过类名获取元素的孩子,我也是开放的。
using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEngine.UI;
public class BasicCombat : MonoBehaviour
{
public KennedyClass playerK;
public pawnClass pawn;
public archerClass archer;
// Use this for initialization
void Start()
{
playerK = GetComponent<KennedyClass>();
pawn = GetComponent<pawnClass>();
archer = GetComponent<archerClass>();
playerK.charHP = playerK.maxHP;
}
// Update is called once per frame
void Update()
{
}
public void Attack()
{
if (gameObject.CompareTag("Pawn"))
{
while (playerK.charHP != 0 & pawn.pawnHP !=0)
{
playerK.charHP -= pawn.pawnDamage;
playerK.HPCount();
Debug.Log("Player - " + playerK.charHP);
var option = EditorUtility.DisplayDialogComplex(
"Attack",
"Do you want to attack?",
"Yes",
"No",
"Exit");
switch (option)
{
case 0:
pawn.pawnHP -= playerK.atkP;
Debug.Log("Pawn - " + pawn.pawnHP);
break;
case 1:
//Exit loop (for now)
break;
case 2:
//Exit loop (for now)
break;
}
}
}
else if (gameObject.CompareTag("Archer"))
{
while (playerK.HP != 0 & pawn.pawnHP != 0)
{
playerK.HP -= archer.archerDamage;
Debug.Log("Player - " + playerK.HP);
var option = EditorUtility.DisplayDialogComplex(
"Attack",
"Do you want to attack?",
"Yes",
"No",
"Exit");
switch (option)
{
case 0:
archer.archerHP -= playerK.atkP;
Debug.Log("Archer - " + archer.archerHP);
break;
case 1:
//Exit loop (for now)
break;
case 2:
//Exit loop (for now)
break;
}
}
}
if (playerK.charHP == 0)
{
Debug.Log("Player death");
Application.LoadLevel(0);
}
if (pawn.pawnHP == 0)
{
Debug.Log("Enemy death");
pawn.GetComponent<Renderer>().enabled = false;
}
if (archer.archerHP == 0)
{
Debug.Log("Enemy death");
archer.GetComponent<Renderer>().enabled = false;
}
}
}
答案 0 :(得分:2)
我创建了一个jsFiddle来比较两个流程的效果,并始终发现$("#div1").find(".myinput");
效率更高。
这对我有意义。 IIRC,#div1 .myinput
将首先找到DOM中的所有.myinput
个元素,然后只返回祖先为#div1
的元素。然而,#div1 .find(.myinput)
只能找到DOM中的第一个#div1
,然后解析它的子节点,有效地减少了所需的解析量,从而产生了更有效的过程。
问题编辑前的上一个答案:
最快的方法就是使用:
var input1 = $('#input');
由于ID属性应该是唯一的,因此添加其他内容毫无意义。