2013-09-22 52 views
0

使用來自Social Mention的小部件腳本 - http://socialmention.com/tools/--。試圖通過添加輸入框來修改,以允許用戶更改社交媒體主題(var smSearchPhrase)。我創建了一個函數[smSearch()]來檢索用戶數據(smTopic),將其分配給一個新變量(var newTopic),然後將該值賦給var smSearchPhrase。分配不起作用。JavaScript - 如何將用戶輸入值分配給腳本中的變量

該函數似乎基於通過警報觀察到的值工作,但是,我無法弄清楚如何在腳本中將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); 
} 

腳本:在原變種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> 
+0

你是什麼意思,它不起作用?它怎麼不工作。看起來它確實分配了值。您什麼時候試圖在smSearchPhrase中顯示值。 –

+0

謝謝比約恩的回覆。我無法從腳本中分配給smSearchPhrase的輸入框(smTopic)中獲取值。對我而言,只有當我手動輸入smSearchPhrase的值時才起作用,例如var smSearchPhrase ='stackoverflow';我希望能回答你的問題。謝謝! -Jim – JimB814

+0

哦,我想我想通了,增加了一個答案。 –

回答

0

我覺得你的表單提交回後臺,你需要從做停止的形式,通過從返回的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在事件或事件上使用了bubble屬性。

+0

謝謝比約恩。我修改了HTML以返回smSearch()onsubmit,並通過返回false返回該函數。警報表明smSearchPhrase已成功地從輸入框中分配了值,但它仍然不起作用。來自SocialMention的腳本使用var smSearchPhrase;好?謝謝你的幫助。 - Jim – JimB814

+0

什麼不起作用?你想要做什麼?它在幹什麼?謝謝。 –

+0

我上傳了文件供您查看。 http://www.webmediapartners.com/contact/social-media-buzz.php。感謝你的協助! - Jim – JimB814

相關問題