javascript - Onclick 更改脚本标签内的功能

标签 javascript jquery html json

下面通过 JSON 提取 Reddit 内容并将其放入相应的 's 中。我自己的迷你reddit。现在您可以看到 URL 是从/r/images 中提取的。我希望能够在输入框中键入“buildapcsales”,并使用从/r/buildapcsales reddit 中提取的脚本重新加载页面的该部分。

我似乎找不到更改脚本内容的方法,或任何其他解决方法。我尝试创建多个文件并让它们在单击时加载,但是不可能构建一个脚本来匹配某人在输入框中键入的所有可能结果。

有没有办法编辑 HTML on-page on.click 的内容?还是通过输入框?通过我的在线研究,我没有发现任何证据表明这是可能的。

<script>
$.getJSON(
    "https://www.reddit.com/r/images.json?jsonp=?",
    function foo(data) {
        $.each(
            // iterate over 10 children, starting at the 0th index
            data.data.children.slice(0,12),
            function (i, post) {
                // put data into the corresponding DIV
                $('#news' + i + ' .redditTitle').append('<a href="https://www.reddit.com/' + post.data.permalink + '">' + post.data.title + '</a>');
                $('#news' + i + ' .redditPermalink').append('<div class="info">expand_more</div>');
                $('#news' + i + ' .redditUps').append(post.data.ups);
                $('#news' + i + ' .redditDowns').append(post.data.downs);
                $('#news' + i + ' .redditPost').append('<p>' + post.data.selftext_html + '</p>');
                $('#news' + i + ' #subredditName').append('<p class="subredditName smalltext alignleft floatleft s-l-padding">r/' + post.data.subreddit + '</p>' );
                $('#news' + i + ' .redditThumbnail').append('<a href="' + post.data.url + '"><img src="' + post.data.thumbnail + '" class="floatleft image news hide">' + '</a>');
                $('#news' + i + ' #redditUsername').append('<p class="smalltext p-color alignleft floatleft s-l-padding redditUsername">'
                    + '<a href="https://www.reddit.com/user/' + post.data.author + '">' + post.data.author + '</a>' + '</p>');
            //Decodes HTML into correct format
            //Also replaces "null" post text with blank value
                $('.redditPost').each(function(){
                    var $this = $(this);
                    var t = $this.text();
                    $this.html(t.replace('&lt','<').replace('&gt', '>'));
                    $this.html(t.replace('null','').replace('null', ''));
                });
            //Checks for "self" tagged images and replaces them with a default placeholder image
                function changeSourceAll() {
                    var images = document.getElementsByTagName('img');
                    for (var i = 0; i < images.length; i++) {
                        if (images[i].src.indexOf('self') !== -1) {
                            images[i].src = images[i].src.replace("self", "/images/default.png");
                        }
                    }
                    for (var i = 0; i < images.length; i++) {
                        if (images[i].src.indexOf('default') !== -1) {
                            images[i].src = images[i].src.replace("self", "/images/default.png");
                        }
                    }
                }
                changeSourceAll();

            }
        )
    }
).error(function() { alert("error"); })

感谢您提前提供任何建议!

最佳答案

I want to be able to type "buildapcsales" in an input box and have that part of the page reload with a script that pulls from the /r/buildapcsales reddit.

为此,您需要一个输入框。

<input type="text" name="subreddit" />

然后,您需要一种方法来获取该输入框的值。

$('input[name="subreddit"]').val();

当字段更改时获取该值也可能很有用。

$('input[name="subreddit"]').on('change', function () ...

然后,您需要构建一个动态 URL。您应该使用 encodeURIComponent 对任何内容进行编码以确保所有特殊字符都能正确转义。

'https://www.reddit.com/r/' + encodeURIComponent(subreddit) + '.json'

此外,我发现您正在使用 JSON-P。不需要... Reddit 有 Access-Control-Allow-Origin: *在它们的 header 中,允许毫无问题地跨域加载这些数据。直接加载数据要可靠得多,并且可以让您正确捕获错误。

I cannot seem to find a way to change the contents of the script, or any other workaround for this.

您无需更改脚本。您需要的是一个可以使用参数调用的函数,然后将该参数连接到 URL 的其余部分。这样,您就可以加载您想要的任何 Reddit 子版 block 。

function loadRedditData(subreddit) {
    $.getJSON('https://www.reddit.com/r/' + encodeURIComponent(subreddit) + '.json').then(function (data) {
        console.log(data);
    });
}

$(function () {
  $('input[name="subreddit"]').on('change', function () {
      loadRedditData($(this).val()); // Pass the value of the input to the loadRedditData function
  });
});

Is there a way to edit the contents of an HTML on-page on.click? Or through an input box? I found no evidence that this is possible through my research online.

当然有可能。否则,像 Stack Overflow、Gmail、Google map 、Facebook 这样的网站,几乎所有这些网站,都是不可能实现的。不确定您在寻找什么,但这里的关键词是“DOM 操作”。 DOM 是文档对象模型...它是表示页面的树结构。通过修改元素,您可以在页面上控制它们。

您需要将想法从“将 HTML 元素编写为格式化指令”转变为“编写可作为树元素解释和加载的 HTML”。一旦您以这种方式看到它,您就不会担心将数据连接到标签中。您只需编辑这些标签的属性即可。这应该可以帮助您开始:

$('.content').append(
  $('<a>')
    .attr('href', 'https://www.reddit.com/' + post.data.permalink)
    .text(post.data.title)
);

如果您将文本连接到 HTML 上下文中,它将被解释为 HTML,这根本不是您想要的。想象一下有人创建了一个标题为 <script src="somethingEvil.js"></script> 的帖子。这就是设置元素属性和文本至关重要的原因之一。

关于javascript - Onclick 更改脚本标签内的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38288830/

相关文章:

javascript - 新服务 worker 的 sw-precache 激活是否保证缓存破坏?

javascript - 为什么我一直在控制台日志中获取 null?

javascript - 如何从另一个函数接收异步函数响应?使用 promise 。

javascript - knockout 嵌套 View 模型

javascript - jQuery 按键不起作用

html - SVG 背景图像不在中心旋转

javascript - 如何从日期时间选择器中获取日期作为字符串?

javascript - 如何使用 jQuery 处理 "defile"文本?

javascript - 使用 AngularJS 将 HTML 文件中的数字限制为小数点后两位

javascript - 在html中创建一个小颜色框