Jquery - 使用一个动态值重复使用多次函数

时间:2016-08-18 23:49:12

标签: javascript php jquery html json

注意:以下是我网站上该网页的工作示例。目前它仅适用于DayZ部分。 https://www.brotherhoodgaming.net/reddit.php

修改 这是我点击redditHeader

的HTML
<div class="redditHeader grey3">
        <p class="white floatleft">
            DayzUnderground
        </p>
        <i class="material-icons redditHeaderCollapse">
            arrow_drop_down
        </i>
    </div>

在过去几个月的StackOverflow的帮助下,我构建了我的第一个网站的骨架。我有一个庞大的Jquery JSON函数,它根据subreddit的URL从reddit中提取数据。我还有3个<div> Dayz BuildaPCSales Bronies 作为测试)。

enter image description here

当我点击任何一个栏时,我希望我的Javascript函数动态加载来自'https://www.reddit.com/r/' + encodeURIComponent(subreddit) + '.json'的数据 - 其中(subreddit)是<div>的val()文本。在此示例中,如果我单击“Dayz”,我希望reddit从r/dayz.json加载数据,而无需手动在代码中键入URL。

这是我的javascript函数。它目前可以成功地用于我手动输入URL的任何reddit。

<script>
$('.redditHeader').click(function() {
    var subreddit = $(this).children('.redditBanner').text();
    loadRedditData(subreddit);
});

function loadRedditData(subreddit) {
    $.getJSON('https://www.reddit.com/r/' + encodeURIComponent(subreddit) + '.json').then(function (data) {
        console.log(data);
        function foo(data) {
            $.each(
                // iterate over 10 children, starting at the 0th index
                data.data.children.forEach(foo); function foo(item, index) { //SAYS I AM MISSING A ")" HERE
                    //Load reddit title in correct div//
                    $('#news' + i + ' .redditTitle').append(
                        $('<a>')
                            .attr('href', 'https://m.reddit.com/' + post.data.permalink)
                            .text(post.data.title)
                    );

                    //Load reddit Score (net UP - DOWN)//
                    $('#news' + i + ' .redditScore').prepend(
                        $('<p>')
                            .attr('class', 'redditUpvoteScore')
                            .text(post.data.score)
                    );

                    //Load reddit post-text in HTML format//
                    $('#news' + i + ' .redditPost').append(
                        $('<p>')
                            .text(post.data.selftext_html)
                    );

                    //Load sub-reddit name in HTML format//
                    /*$('#news' + i + ' .subRedditName').append(
                     $('<p>')
                     .attr('class', 'subRedditFormat')
                     .text('r/' + post.data.subreddit)
                     );*/

                    //Load post thumbnail URL into an <a> tag wrapping the image//
                    $('#news' + i + ' .redditThumbnail').append(
                        $('<a>')
                            .attr('href', post.data.url)
                            .attr('class', 'thumbURL')
                    );

                    //Load actual thumbnail into the <a> wrapper tag with the thumbURL class//
                    $('#news' + i + ' .thumbURL').append(
                        $('<img>')
                            .attr('src', post.data.thumbnail)
                            .attr('class', "image news hide floatleft")
                    );

                    //Load reddit Username and URL into container DIV//
                    $('#news' + i + ' .userNameContainer').append(
                        $('<a>')
                            .attr('class', 'redditUserName')
                            .attr('href', 'https://m.reddit.com/user/' + post.data.author)
                            .text(post.data.author)
                    );

                    // Convert post creation time to local time//
                    var utcSeconds = post.data.created_utc;
                    var d = new Date(0);
                    // The 0 is the key, which sets the date to the epoch
                    d.setUTCSeconds(utcSeconds);

                    //Use Moment.js to calculate relative date and append to DIV//
                    $('#news' + i + ' .redditDate').append(
                        moment(d).fromNow()
                    );

                    //Decodes HTML into correct format by replacing unescaped characters//
                    $('.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 with 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", "css/images/default.jpg");
                            }
                        }
                        for (var i = 0; i < images.length; i++) {
                            if (images[i].src.indexOf('default') !== -1) {
                                images[i].src = images[i].src.replace("self", "css/images/default.jpg");
                            }
                        }
                        for (var i = 0; i < images.length; i++) {
                            if (images[i].src.indexOf('https://www.brotherhoodgaming.net/default') !== -1) {
                                images[i].src = images[i].src.replace("https://www.brotherhoodgaming.net/default", "css/images/default.jpg");
                            }
                        }
                    }
                    changeSourceAll();
                }
            )
        }
    });
}

这是我用类“redditHeader”从<div>获取文本值的可怕尝试。

$('.redditHeader').each().on('click', function (){
$('p[class="white"]').val();
})

提前感谢您提供任何可能的帮助。我很难过!

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

$('.redditHeader').click(function (event){
    var subreddit = $(event.currentTarget).find('.white').text();
    loadRedditData(subreddit);
 })

$(event.currentTarget)获取已单击的元素,find()将获取此元素的子元素。最后,我调用loadRedditData(subreddit)。

我压制了each(),因为我真的不明白你试图用它来实现的目标。

答案 1 :(得分:1)

您无法获得.val()代码的<p>!使用.text()

$('.redditHeader').click(function() {
  var subreddit = $(this).children('.white').text();
  loadRedditData(subreddit);
});