jquery只添加一次span元素

时间:2015-12-02 12:07:47

标签: javascript jquery html

我把表格放入表格(我只显示了第一行。所有其他都是相同的):

<tr>
    <td><label for="login">Username</label></td>
    <td>
       <input id="login" type="text" path="login" placeholder="Enter Login"
                                       oninvalid="this.setCustomValidity('Please fill this field - it is mandatory')"
                                       oninput="setCustomValidity('')">
    </td>
</tr>

我想要做的是先添加&#34;输入&#34;元素&#34;跨度&#34;元素,但只有一次,意​​思是在添加之前 - 检查是否存在。换句话说,结果应该是这样的:

<span></span><input ...

代码就像这样:

var spanvar = "<span/>";
 if($('input').prev("span").length==0) --> check if there is no <span> before
 {
    $("input".before(spanvar)); ---> add span element but only once
 }

2 个答案:

答案 0 :(得分:0)

你可以做这样的事情

// Iterate through every input
$("input").each(function(){

  // If no span
  if($(this).prev("span").length==0){

    // Add span before this
    $(spanvar).insertBefore(this);
  }
});

答案 1 :(得分:0)

检查当前元素是否为 public void run () { try{ FileWriter writer = new FileWriter("datalogging.txt", true); PrintWriter print = new PrintWriter(writer); InputStream is = sock.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); fileName = br.readLine(); System.out.println(fileName); System.out.println("Message recieved"); if (fileName.charAt(0) == 'R') { download(); print.println(df.format(dateobj) + " : " + InetAddress.getLocalHost().getHostAddress() + " : " + "download" ); } else{ upload(); print.println(df.format(dateobj) + " : " + InetAddress.getLocalHost().getHostAddress() + " : " + "upload" ); } print.close(); writer.close(); } catch (Exception e) { System.out.println(e); } }

类型
span

所以你可以推荐

$(this).prev().is('span')
相关问题