如何获取最接近html元素标记的文本

时间:2015-07-04 12:24:31

标签: javascript jquery

我有这个html片段:

<label>
  <input type="checkbox"/>
  text here
</label>

在我的js中,我想在这里检索&#39;文本&#39;值

这是我的js:

$('input[type=checkbox]').click(function (e) {
var msg = e.target.closest???
});

6 个答案:

答案 0 :(得分:5)

您可以使用DOM节点nextSibling属性:

$('input[type=checkbox]').click(function (e) {
    var msg = this.nextSibling.nodeValue;
    console.log(msg);
});

&#13;
&#13;
$('input[type=checkbox]').click(function (e) {
    var msg = this.nextSibling.nodeValue;
    alert(msg);    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>
    <input type="checkbox" />text here
</label>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用contents()

$('input[type=checkbox]').click(function(e) {
  var contents = $(this).closest('label').contents();
  var msg = contents[2];
  console.log(msg);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<label>
  <input type="checkbox" />text here
</label>

或者在您的简单案例中,text()trim()

$('input[type=checkbox]').click(function(e) {
  var msg = $(this).closest('label').text().trim();
  console.log(msg);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<label>
  <input type="checkbox" />text here
</label>

答案 2 :(得分:0)

parent()text()似乎是获取该文字的好方法。 单击下面的运行,然后单击您的标签。

&#13;
&#13;
$('input[type=checkbox]').click(function (e) {
var msg = $(this).parent().text()
$('#t').text(msg)
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox"/>
  text here
</label>

<p id="t"></p>
&#13;
&#13;
&#13;

关于nextSibling解决方案,如果您的文字位于<input>之前,则无法返回...因为您只有<label>作为父级,在此特定情况下,我个人建议使用<input> parent(),然后使用text(),它将始终返回<label>内的所有文字,而不会否则:复选框没有关联的文本。

答案 3 :(得分:0)

尝试使用javascript的nextSibling属性。

代码段:

$('input[type=checkbox]').click(function (e) {
    var ele = $(this);
    var msg = ele[0].nextSibling.nodeValue;
    alert(msg);
    });

希望这可以帮助你!!!

答案 4 :(得分:0)

您可以使用jQuery的/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package generatekeypair; import iaik.pkcs.pkcs11.Mechanism; import iaik.pkcs.pkcs11.MechanismInfo; import iaik.pkcs.pkcs11.Module; import iaik.pkcs.pkcs11.Session; import iaik.pkcs.pkcs11.Slot; import iaik.pkcs.pkcs11.Token; import iaik.pkcs.pkcs11.TokenException; import iaik.pkcs.pkcs11.TokenInfo; import iaik.pkcs.pkcs11.objects.KeyPair; import iaik.pkcs.pkcs11.objects.Object; import iaik.pkcs.pkcs11.objects.RSAPrivateKey; import iaik.pkcs.pkcs11.objects.RSAPublicKey; import iaik.pkcs.pkcs11.wrapper.Functions; import iaik.pkcs.pkcs11.wrapper.PKCS11Constants; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Random; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Administrador */ public class CrearCertiPar { private Module pkcs11Module; public CrearCertiPar(String librarayPath) throws TokenException { try { pkcs11Module = Module.getInstance(librarayPath); pkcs11Module.initialize(null); generarParcerti(); } catch (IOException ex) { Logger.getLogger(CrearCertiPar.class.getName()).log(Level.SEVERE, null, ex); } } public void generarParcerti() throws TokenException { Scanner teclado = new Scanner (System.in); Slot[] slots = pkcs11Module.getSlotList(Module.SlotRequirement.TOKEN_PRESENT); if (slots.length == 0) { //No tokens connected System.out.println("Sorry, Couldn't find any token"); } else { //Let's get the first slot Slot selectedSlot = slots[0]; //Let's get the connected token Token token = selectedSlot.getToken(); //Get the token infos TokenInfo tokenInfo = token.getTokenInfo(); //System.out.println(tokenInfo); Session session = token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RW_SESSION, null, null); //System.out.println(session); if (tokenInfo.isLoginRequired()) { if (tokenInfo.isProtectedAuthenticationPath()) { session.login(Session.UserType.USER, null); // the token prompts the PIN by other means; e.g. PIN-pad } else { System.out.print("Enter user-PIN or press [return] to list just public objects: "); System.out.flush(); //String userPINString = teclado.next(); String userPINString = "12345678"; System.out.println(); System.out.print("listing all" + ((userPINString.length() > 0) ? "" : " public") + " objects on token"); if (userPINString.length() > 0) { // login user session.login(Session.UserType.USER, userPINString.toCharArray()); } } } System.out.println("############################# Generating new 1024 bit RSA key-pair ########################################"); HashSet supportedMechanisms = new HashSet(Arrays.asList(token.getMechanismList())); MechanismInfo signatureMechanismInfo; System.out.println("supportedMechanisms\n"+supportedMechanisms); if (supportedMechanisms.contains(Mechanism.RSA_PKCS_KEY_PAIR_GEN)) { signatureMechanismInfo = token.getMechanismInfo(Mechanism.RSA_PKCS_KEY_PAIR_GEN); } else if (supportedMechanisms.contains(Mechanism.RSA_X_509)) { signatureMechanismInfo = token.getMechanismInfo(Mechanism.RSA_X_509); } else if (supportedMechanisms.contains(Mechanism.RSA_9796)) { signatureMechanismInfo = token.getMechanismInfo(Mechanism.RSA_9796); } else if (supportedMechanisms.contains(Mechanism.RSA_PKCS_OAEP)) { signatureMechanismInfo = token.getMechanismInfo(Mechanism.RSA_PKCS_OAEP); } else { signatureMechanismInfo = null; } // System.out.println("signatureMechanismInfo\n"+signatureMechanismInfo); Mechanism keyPairGenerationMechanism = Mechanism.RSA_PKCS_KEY_PAIR_GEN; RSAPublicKey rsaPublicKeyTemplate = new RSAPublicKey(); RSAPrivateKey rsaPrivateKeyTemplate = new RSAPrivateKey(); rsaPublicKeyTemplate.getObjectClass().setPresent(true); rsaPublicKeyTemplate.getToken().setBooleanValue(Boolean.TRUE); rsaPublicKeyTemplate.getPrivate().setBooleanValue(Boolean.FALSE); rsaPublicKeyTemplate.getModifiable().setBooleanValue(Boolean.TRUE); rsaPublicKeyTemplate.getKeyType().setPresent(true); byte[] id = new byte[5]; new Random().nextBytes(id); rsaPublicKeyTemplate.getId().setByteArrayValue(id); rsaPublicKeyTemplate.getLocal().setBooleanValue(Boolean.TRUE); rsaPublicKeyTemplate.getKeyGenMechanism().setMechanism(keyPairGenerationMechanism); rsaPublicKeyTemplate.getEncrypt().setBooleanValue(Boolean.TRUE); rsaPublicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE); rsaPublicKeyTemplate.getVerifyRecover().setBooleanValue(Boolean.TRUE); rsaPublicKeyTemplate.getWrap().setBooleanValue(Boolean.TRUE); byte[] mod = new byte[256]; new Random().nextBytes(mod); rsaPublicKeyTemplate.getModulus().setByteArrayValue(mod); rsaPublicKeyTemplate.getModulusBits().setLongValue(new Long(2048)); byte[] publicExponentBytes = { 0x01,0x00,0x01 }; // 2^16 + 1 rsaPublicKeyTemplate.getPublicExponent().setByteArrayValue(publicExponentBytes); rsaPrivateKeyTemplate.getObjectClass().setPresent(true); rsaPrivateKeyTemplate.getToken().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getPrivate().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getModifiable().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getKeyType().setPresent(true); rsaPrivateKeyTemplate.getId().setByteArrayValue(id); rsaPrivateKeyTemplate.getLocal().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getKeyGenMechanism().setMechanism(keyPairGenerationMechanism); rsaPrivateKeyTemplate.getSensitive().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getDecrypt().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getSignRecover().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getUnwrap().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getExtractable().setBooleanValue(Boolean.FALSE); rsaPrivateKeyTemplate.getAlwaysSensitive().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getNeverExtractable().setBooleanValue(Boolean.TRUE); rsaPrivateKeyTemplate.getModulus().setByteArrayValue(mod); rsaPrivateKeyTemplate.getPublicExponent().setByteArrayValue(publicExponentBytes); System.out.println("*********************************\n"+rsaPublicKeyTemplate); System.out.println("*********************************\n"); System.out.println("*********************************\n"+rsaPrivateKeyTemplate); System.out.println("*********************************\n"); KeyPair generatedKeyPair = session.generateKeyPair(keyPairGenerationMechanism, rsaPublicKeyTemplate, rsaPrivateKeyTemplate); // RSAPublicKey generatedRSAPublicKey = (RSAPublicKey) generatedKeyPair.getPublicKey(); // RSAPrivateKey generatedRSAPrivateKey = (RSAPrivateKey) generatedKeyPair // .getPrivateKey(); // System.out.println("Success"); // System.out.println("The public key is"); // System.out.println("_______________________________________________________________________________"); // System.out.println(generatedRSAPublicKey); // System.out.println("_______________________________________________________________________________"); // System.out.println("The private key is"); // System.out.println("_______________________________________________________________________________"); // System.out.println(generatedRSAPrivateKey); // System.out.println("_______________________________________________________________________________"); // } } }功能

.closest()

答案 5 :(得分:0)

以下代码段适用于您的HTML

&#13;
&#13;
$('input[type=checkbox]').parent().text();
&#13;
&#13;
&#13;