2017-02-18 131 views
0

任何人都可以告訴我如何從span元素克隆並通過單擊span元素本身追加到輸入值? 這是腳本。Jquery克隆並附加到輸入值

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
    <script> 
 
    $(document).ready(function() { 
 
     $("span#username").click(function() { 
 
     $("span#username").clone().appendTo("#test"); 
 

 

 
     }); 
 
    }); 
 
    </script> 
 
</head> 
 

 
<body> 
 

 
    <span id="username"> User </span><br><br> 
 
    <input type="text" id="test" value="" /> 
 

 

 
</body> 
 

 
</html>

回答

1

你必須設置輸入(jQuery.val())的跨度(jQuery.text())的文本內容的價值是這樣的:

// IDs are enough 
$("#username").click(function() { 
    $("#test").val($(this).text()); // this is the span beign clicked 
}); 

沒有jQuery的:

document.getElementById("username").addEventListener("click", function() { 
    document.getElementById("test").value = this.textContent; 
}); 
+0

我想知道它是否可能在JavaScript以及? – Neof

+0

@Neof我添加了沒有jQuery的代碼,只是香草JS! –