使用指定的用户名从tumblr中提取javascript

时间:2015-07-28 21:24:02

标签: javascript tumblr

我正在尝试使用相当简单的代码。它的本质只是获取用户输入,将其附加到源URL,然后使用脚本显示适当的tumblr源。

我花了一些时间在这上面,而且我无法理解javascript如何运作这样做。

这是我到目前为止所做的:

<html>
<body>
    <form>
        Tumblr Username:<br>
        <input type="text" name="username">
        <br>
        <br>
        <input type="submit" value="Submit">
    </form>
    <script type="text/javascript" src= username + ".tumblr.com/js"></script>
</body>
</html>

提前致谢。

2 个答案:

答案 0 :(得分:1)

JavaScript的工作方式是,您需要一个事件来附加代码的运行。在您的情况下,表单的submit事件。此外,您无法在尝试时计算HTML中的值;你需要代码来操纵HTML(DOM)。以下是您如何做到这一点的示例:

<html>
<body>
    <form onSubmit="handleSubmit(event)">
        Tumblr Username:<br>
        <input type="text" name="username">
        <br>
        <br>
        <input type="submit" value="Submit">
    </form>
    <script id="theScript" type="text/javascript"></script>
    <script>
      function handleSubmit(e) {
        e.preventDefault(); // Keep the form from actually submitting
        var username = document.querySelector('[name="username"]').value;
        document.getElementById('theScript').src = username + '.tumblr.com/js';
      }
    </script>
</body>
</html>

答案 1 :(得分:0)

Because the JS file that is on username.tumblr.com uses document.write, I think it'd be better to just load the actual url of the user in an iframe, as this wouldn't require you to refresh the page, while creating a mini page inside your page.

This won't work on the snippet tool here or on JSFiddle, but I've tested it on a web server:

<html>

<body>
  <script>
    function getUN() {
      var username = document.getElementsByName("username")[0].value;
      document.getElementById("tumblrframe").src = "http://" + username + ".tumblr.com";

    }
  </script>

  Tumblr Username:
  <br>
  <input type="text" name="username">
  <br>
  <br>
  <button onclick="getUN()">Submit</button>
  <br/>
  <br/>
  <iframe id="tumblrframe" width="80%" height="600px"></iframe>

</body>

</html>