JavaScript - 如何将用户输入值分配给脚本中的变量

JavaScript - How to assign user input value to variable inside script

本文关键字:分配 脚本 变量 输入 用户 JavaScript      更新时间:2023-09-26

使用小部件脚本--http://socialmention.com/tools/--来自Social Mention。尝试通过添加输入框进行修改,以允许用户更改社交媒体主题(var smSearchPhrase)。我创建了一个函数[smSearch()]来检索用户数据(smTopic),将其分配给一个新变量(var newTopic),然后将该值分配给var smSearchPhrase。作业不起作用。

该函数似乎基于通过警报观察到的值工作,但是,我无法弄清楚如何将变量 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 = 'social mention';

    <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()(此处未显示),但这仅适用于所有浏览器,当您还包含像 jQuery 这样的 JavaScript 库时,因为某些版本的 IE 在事件或其他东西上使用气泡属性。