将变量追加到href的末尾

Append variable at end of href?

本文关键字:href 变量 追加      更新时间:2023-09-26

我正在尝试根据用户搜索生成一个twitter流小部件。使用他们的api,如果搜索词是已知的,比如"corgi",就很容易创建一个。这是我的代码:

我希望能够删除"柯基",并用他们搜索的任何内容替换它。

编辑:经过一些在线研究,我认为解决方案比在href中添加一个变量要复杂一些。现在我使用这个:

$(document).ready(function() {
// Upon form submission
$("#formy").submit( function(e) {
    // Stop the <form> from refreshing
    e.preventDefault();
    // Store the user's input
    var id = $('#searchbar').val(); 
    //Make REST call to Twitter API
    $.ajax({
        url: '/search',
        type: 'POST',
        data: {id:id}, 
        dataType: 'text',
        success: function(data) {
            // Redirect to the reults page   
            window.location.href = '/test';
            data = JSON.parse(data);
            //console.log(data);
            // Store data from REST call in local storage
            localStorage.setItem("count", "we analyzed...");
            localStorage.setItem("result1", data.county + " tweets");
            localStorage.setItem("totals", "with a total sentiment score of..");
            localStorage.setItem("result2", data.totalSentiments);
            localStorage.setItem("head",id);
        },
        error: function(jqXHR, textStatus, errorThrown){
            console.log("An error occured.")
            alert(textStatus, errorThrown);
        }
    });
});
// Modify the divs to display the results on the page
jQuery(document).ready(function(){
var id = localStorage.head;
if (localStorage.count) {
    $("#count").text(localStorage.count);
}
if (localStorage.result1) {
    $("#result1").text(localStorage.result1);
}
if (localStorage.totals) {
    $("#totals").text(localStorage.totals);
}
if (localStorage.result2) {
    $("#result2").text(localStorage.result2);
}
if (localStorage.head) {
    $("#head").text("You Searched: " + localStorage.head);
}
localStorage.clear();
//localStorage.removeItem("count");
 window.twttr = (function (d,s,id) {
  console.log("TWITTER  RULES!!!");
      var t, js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;
      js.src="https://platform.twitter.com/widgets.js";
      fjs.parentNode.insertBefore(js, fjs);
      return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });
  (document, "script", "twitter-wjs");

twttr.ready(function (twttr) {
  console.log("TWITTER  RULES!!!");
    twttr.widgets.createTimeline(
  '721140436522373121',
  document.getElementById('timeline'),
  {
    width: '400',
    height: '440',
    related: localstorage.head
  }).then(function (el) {
    console.log("Embedded a timeline.")
  });
    });
    }
);




});
});

问题是,虽然代码中的其他一切都很好,但twttr函数似乎什么都不做。之所以所有东西都在一个函数中,是因为我依赖本地存储来存储用户输入。。。

这应该可以工作。只需将SUBMIT BUTTON ID设置为提交按钮的id,将SEARCH INPUT ID设置为用户输入的id

$(SUBMIT BUTTON ID).click(function() {
    var htag = $(SEARCH INPUT ID).val();
    $("twitter-timeline").prop("href", "https://twitter.com/hashtag/"+htag);
});