简体   繁体   English

使用jQuery,我如何Ajax将文本加载到多个.class中而不是#id中?

[英]Using jQuery, how can I ajax load text into multiple .classes rather than #id's?

On my website I have a commenting form which tells you how long ago a comment was posted. 在我的网站上,我有一个评论表格,告诉您多久前发布评论。
Below is a code to reload only the span containing the date every 10 seconds, NOT the entire comments div (to prevent page-lag) 下面的代码仅每10秒重新加载一次包含日期的跨度,而不是整个注释div(以防止出现页面滞后)

$(function(){
     setInterval(
     function(){ 
     var id = $('.date').html();
     $('.date').load('/comdate.php?id=' + id); }
     ,10000);
});

my function is not working, and I don't really want to make a seperate function for every comment's date field. 我的功能无法正常工作,我真的不想为每个评论的日期字段都设置单独的功能。 Please may someone point out my problem? 请有人指出我的问题吗? Thanks 谢谢

EDIT 编辑
I am using this in javascript to change the time to a readable date 我在javascript中使用它来将时间更改为可读的日期

   function prettyDate(time){
    var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);

    if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
        return;

    return day_diff == 0 && (
            diff < 60 && "just now" ||
            diff < 120 && "1 minute ago" ||
            diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
            diff < 7200 && "1 hour ago" ||
            diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
        day_diff == 1 && "Yesterday" ||
        day_diff < 7 && day_diff + " days ago" ||
        day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
    jQuery.fn.prettyDate = function(){
        return this.each(function(){
            var date = prettyDate(this.title);
            if ( date )
                jQuery(this).text( date );
        });
    };

This returns GMT+1 though because thats where I am. 这将返回GMT + 1,因为那是我所在的位置。 how do I change this function to make the javascript timezone GMT aswell? 如何更改此功能,以使javascript时区也成为GMT?

For me i would change my ajax request to send the unix timespan only once and i would do all my calculations in javascript. 对我来说,我将更改ajax请求以仅发送一次unix时间跨度,并且我将使用javascript进行所有计算。

var periods = ["second", "minute", "hour", "day", "week", "month", "year", "decade"];
var lengths = ["60","60","24","7","4.35","12","10"];

function nicetime(user_date)
{
    if(typeof user_date == "undefined" ) {
        return "No date provided";
    }

    var now  = new Date().getTime();
    var unix_date = user_date;

    // check validity of date
    if(unix_date == "") {   
        return "Bad date";
    }

    // is it future date or past date
    if(now > unix_date) {   
        var difference = now - unix_date;
        var tense = "ago";
    } else {
        var difference = unix_date - now;
        var tense      = "from now";
    }
    difference = difference/1000; //from milliseconds to seconds;
    for(var j = 0; difference >= lengths[j] && j < lengths.length-1; j++) {
        difference /= lengths[j];
    }

    difference = Math.round(difference);

    if(difference != 1) {
        periods[j] += "s";
    }

   return difference+" "+periods[j]+" "+tense;
}


console.log(nicetime(1378632182334));

Example: 例:

http://jsfiddle.net/F6H2w/ http://jsfiddle.net/F6H2w/

NOTE The only thing that i changed in your function is: 注意我在您的功能中所做的唯一更改是:

difference = difference/1000; //from milliseconds to seconds;

your code was dealing with the differences variable in milliseconds which should be in seconds. 您的代码处理的差异变量以毫秒为单位,应以秒为单位。

The suggestion made by @ra_htial in his first comment sounds like the best one, because it doesn't poll the server needlessly with requests which could be managed on the client side with javascript. @ra_htial在他的第一条评论中提出的建议听起来像是最好的建议,因为它不会不必要地轮询请求,而请求可以使用javascript在客户端进行管理。 So my suggestion is to add a data-date attribute to your .date span elements, which would contain the date and time in plain format, which can be decoded in javascript and used to update the human readable date. 因此,我的建议是向.date span元素添加data-date属性,该属性应包含纯格式的日期和时间,可以使用javascript进行解码并用于更新人类可读的日期。

Here's how the html should look like with static data: 这是带有静态数据的html的外观:

<span class="date" data-date="2013-09-08 12:37">1 min ago</span>

Or outputted from your php script: 或从您的php脚本输出:

<span class="date" data-date="<?php echo $date; ?>"><?php echo nicetime($date); ?></span>

And here's the javascript that updates the date content (I used the formatting function from this article http://www.zachleat.com/web/yet-another-pretty-date-javascript/ but there are other alternatives like John Resig's Pretty Date ): 这是更新日期内容的javascript(我使用了本文http://www.zachleat.com/web/yet-another-pretty-date-javascript/中的格式化功能,但还有其他替代方法,例如John Resig的Pretty Date ):

setInterval(function()
{ 
    $('.date').each(function()
    {
        var $this = $(this);
        $this.html(humane_date($this.data('date')));
    });
}, 10000);

EDIT 编辑

Here's a fiddle that illustrates the functionality http://jsfiddle.net/FXERS/ . 这是一个小提琴,说明了功能http://jsfiddle.net/FXERS/ You would need to change the data-date attribute for one of the elements in the fiddle, to your current time to see it get updated. 您需要将小提琴中的元素之一的data-date属性更改为当前时间,以查看其更新。

Doesn't look like you can use the .load() method on multiple elements, but you could fetch the date once into a variable and then update all the other elements: 看起来您可以在多个元素上使用.load()方法,但是您可以一次将日期提取到变量中,然后更新所有其他元素:

$.get('/comdate.php?id=' + id, function(data) {
    $('.date').each( function() { $(this).html(data); } );
});

Which updates all the elements. 哪个更新所有元素。 Although pointed out above in the comments, you're not doing anything in that script you couldn't do in JS with a bit of work. 尽管上面的注释中已指出,但是您在该脚本中并没有做任何工作,而这在JS中是无法完成的。

Edited to add Look for at the Date object in JavaScript, it can get the current time and parse it -- everything else in your function is just logic which is easy to translate. 经过编辑后,在JavaScript中添加了 Look at at Date对象,它可以获取当前时间并进行解析-函数中的其他所有内容都只是易于翻译的逻辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以将jQuery动态加载到局部变量而不是窗口吗? - Can I load jQuery dynamically to a local variable rather than to window? 如何让 jQuery 执行同步而不是异步的 Ajax 请求? - How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request? 如何使用jQuery而不是angular的jqLit​​e从指令的链接函数的&#39;element&#39;参数中选择具有特定ID的元素? - How to select an element with a specific id from a directive's linking function's 'element' parameter, using jQuery rather than angular's jqLite? 使用jQuery时,是否应该使用ID以外的类? - Should I be using classes more than ID's when utilizing jQuery? jQuery .load结果进入&#39;调用&#39;div(而不是指定的id)? - jQuery .load result into the 'calling' div (rather than a specified id)? 如何使用jquery / AJAX加载外部CSS文件? - How can I Load external Css files Using jquery/AJAX? 如何获取第一个元素而不是在 jQuery 中使用 [0]? - How do I get first element rather than using [0] in jQuery? 我如何使用js或jquery序列化具有倍数ID的多种形式 - How can i serialize multiple forms with multiples id's using js or jquery 如何使用端点而不是一个 ID 传递要删除的 ID 数组 - How to pass an array of id's to delete using an endpoint rather than just one Id 我如何将jQuery事件仅应用于页面上的一个输入而没有类和ID - How can I apply jQuery event to only one input on page without classes and id's
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM