簡體   English   中英

僅將段落的第一個單詞保存在javascript變量中

[英]Saving only the first word of a paragraph in a javascript variable

我正在嘗試將段落存儲在javascript變量中。 我在一個表內有多個按鈕,每個按鈕都有一個不同的值,每個按鈕的值都是一個小的文本段落。 當我單擊按鈕時,將當前按鈕的值保存在名為“ input”的javascript變量中。

單擊按鈕時,我還將加載一個名為“ contactForm”的html表單,並在該表單內顯示按鈕值。

該功能運行良好,但問題是當我將按鈕的值保存在('input')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> 

它很簡單而且很有效……我只是不包括您編寫的其他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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM