javascript - jQuery 不起作用,除非我复制并粘贴到谷歌浏览器控制台,它运行良好

标签 javascript jquery html css

这是我的 HTML:

<textarea cols="5" disabled id="textareRSAKeypair">
  @Model["keypair"]
</textarea>

<a href="#" class="btn btn-primary" id="downloadKeypair">DownLoad Key</a>

这是我的 jQuery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
  $("a#downloadKeypair").click(function () {
    var now = new Date().toString();
    var filename = 'RSAKeyPair_' + now + ".txt";
    $("a#downloadKeypair").attr('Download', filename);

    this.href = "data:text/plain;charset=UTF-8," + encodeURIComponent($('#textareRSAKeypair').text());
  });
</script>

我的 jQuery 代码在页面上不起作用,但是当我将它复制并粘贴到控制台 (google chrome) 时,它运行良好。我不知道为什么。我尝试添加 document.load 方法,但它仍然不起作用。

最佳答案

尝试就绪事件:

$( document ).ready(function() {
    $("a#downloadKeypair").click(function () {
        var now = new Date().toString();
        var filename = 'RSAKeyPair_' + now + ".txt";
        $("a#downloadKeypair").attr('Download', filename);
        this.href = "data:text/plain;charset=UTF-8," + encodeURIComponent($('#textareRSAKeypair').text());
    });
});

关于javascript - jQuery 不起作用,除非我复制并粘贴到谷歌浏览器控制台,它运行良好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22874040/

相关文章:

php - 如何限制用户下载或保存pdf文件?

jquery - Cufon 和 IE6/7/8 的问题

html - 不要在背景图像的 div 中显示文本

javascript - 访问模板的实例范围并注入(inject)数据

javascript - 无法使用ajax添加评论

javascript - 如何知道浏览器选项卡在加载 Javascript 时是否聚焦?

html - 网格布局在 Firefox 中被破坏,但在 Chrome 中却没有

android - 如何在 Android 中保存(下载)包含所有图像、CSS 等的 HTML 页面?

php - 仅在元素未被拖动时获取输出

javascript - 跨度垂直对齐