簡體   English   中英

JavaScript-如何將用戶輸入值分配給腳本中的變量

[英]JavaScript - How to assign user input value to variable inside script

使用小部件script-- http://socialmention.com/tools/--從社會表揚。 試圖通過添加輸入框進行修改,以允許用戶更改社交媒體主題(var smSearchPhrase)。 我創建了一個函數[smSearch()]來檢索用戶數據(smTopic),將其分配給新變量(var newTopic),然后將該值分配給var smSearchPhrase。 分配不起作用。

該功能似乎基於通過警報觀察到的值工作,但是,我無法弄清楚如何在腳本內將值從var newTopic分配給var smSearchPhrase。 我通過將腳本放置在函數中進行了實驗,但這也不起作用。 任何幫助表示贊賞。

如果我未能提供所有必要的信息,請告知。 感謝您的協助。

HTML:

<form>
   <label for="smTopic">Enter topic:</label>
   <input type="text" id="smTopic">
   <button onclick="smSearch()">Submit</button>
   <input type="reset">
</form>

功能:(包括警報以檢查值)

function smSearch(){ 
   var newTopic=document.getElementById("smTopic").value;
       if(newTopic === ""){
          alert("Please enter new social media topic.");                                                  
       }else{
          alert("New topic: " + newTopic);
          smSearchPhrase = newTopic; 
          alert("Value of smSearchPhrase: " + smSearchPhrase);
}

腳本:原始的var smSearchPhrase已分配了值,例如var smSearchPhrase ='社交提及';

    <script type="text/javascript"> 
      // search phrase (replace this)
      var smSearchPhrase;
      // title (optional)
      var smTitle = 'Realtime Buzz';
      // items per page
      var smItemsPerPage = 7;
      // show or hide user profile images
      var smShowUserImages = true;
      // widget font size in pixels
      var smFontSize = 11;
      // height of the widget
      var smWidgetHeight = 800;
      // sources (optional, comment out for "all")
      //var smSources = ['twitter', 'facebook', 'googleblog', 'identica'];
    </script>
    <script type="text/javascript" language="javascript" src="http://socialmention.s3.amazonaws.com/buzz_widget/buzz.js"></script>

我認為您的表單正在提交回后端,您需要通過從onsubmit返回false或取消事件來阻止表單執行此操作。

所以這應該工作:

<form onsubmit="return smSearch();">
   <label for="smTopic">Enter topic:</label>
   <input type="text" id="smTopic">
   <button>Submit</button>
   <input type="reset">
</form>

並在JavaScript中返回false:

function smSearch(){ 
       var newTopic=document.getElementById("smTopic").value;
       if(newTopic === ""){
          alert("Please enter new social media topic.");                                                  
       }else{
          alert("New topic: " + newTopic);
          smSearchPhrase = newTopic; 
          alert("Value of smSearchPhrase: " + smSearchPhrase);
       }
       return false;
}

就個人而言,我會在事件參數上使用preventDefault()(此處未顯示),但是僅當您還包括JavaScript庫(如jQuery)時,該方法才能在所有瀏覽器上使用,因為某些版本的IE在事件或其他內容上使用bubble屬性。

暫無
暫無

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

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