我正在尝试将段落存储在javascript变量中。我在一个表内有多个按钮,每个按钮都有不同的值,每个按钮的值是一个小文本段。当我单击按钮时,将当前按钮值保存在名为“输入”的javascript变量中。
单击按钮时,我还会加载名为" contactForm"的html表单。我在该表单中显示按钮值。
功能正常,但问题是,当我在('输入')js变量中保存按钮的值时,它只保存段落的第一个单词,有没有办法解决这个问题?
<html>
<div id="contactForm" >
<p><h4><i>First Choose the clients and then the file which will be uploaded in order to proced</i></h4></2>
<hr>
<input type="text" id="someInput" name="someInput"></input>
<hr>
</div>
<script>
var input; //prepare var to save contact name/ PLACE outside document ready
$(function() {
// contact form animations
$('button[id="contactbutton"]').click(function() {
input = $(this).val(); //set var input to value of the pressed button
document.getElementById("someInput").value = input;
$('#contactForm').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
</script>
<html>
&#13;
答案 0 :(得分:0)
这很简单,它的工作原理......我只是没有包含你写的额外的jQuery,就像从段落中获取第一个单词一样,它确实这样做了。
<div id="contactForm" >
<p>First Choose the clients and then the file which will be uploaded in order to proced</p>
<hr>
<input type="text" id="someInput" name="someInput">
<hr>
</div>
<br>...
<br>
<h4>Demo</h4>
<button id ="contactbutton">Click Me</button>
<script>
/**
* @description the purpose of this function is to demonstrate how to
* get the first word of a paragraph, sentence, etc.
*/
!function() {
var btn = document.querySelector('button[id="contactbutton"]');
btn.addEventListener("click", function(){
// get the paragraph tag text
var para = document.querySelector("#contactForm p").textContent;
console.log(para);
// break the paragraph into an arraywor each word seperated by a space
// index 0 = first element in the array
var word = para.split(" ")[0];
console.log(word);
// another example
var inp = document.querySelector("input#someInput");
var inpVal = inp.value;
console.log(inpVal);
var word2 = inpVal.split(" ")[0];
console.log(word2);
});
}();
</script>