帮助将一些 Prototype JavaScript 移植到 jQuery
我已经通过使用 will_paginate 插件的 示例代码在我的 Rails 应用程序中实现了一些 AJAX 分页——这显然是使用原型。
但如果我想改用 jQuery 来进行未来的添加,我真的不想让 Prototype 的东西也闲置(是的,我知道 这是可能的)。我已经很多年没有写过 JavaScript 了,更不用说研究 Prototype 和 jQuery...所以我可以使用一些帮助将这一点转换为 jQuery 兼容的语法:
document.observe("dom:loaded", function() {
// the element in which we will observe all clicks and capture
// ones originating from pagination links
var container = $(document.body)
if (container) {
var img = new Image
img.src = '/images/spinner.gif'
function createSpinner() {
return new Element('img', { src: img.src, 'class': 'spinner' })
}
container.observe('click', function(e) {
var el = e.element()
if (el.match('.pagination a')) {
el.up('.pagination').insert(createSpinner())
new Ajax.Request(el.href, { method: 'get' })
e.stop()
}
})
}
})
提前致谢!
编辑: Nick Craver 的回答让我完成了 90% 的工作,所以我只需要选择足够的 jQuery 来进行 HTML 元素替换。代替 Nick 的 $.get($(this).attr("href"));
行,输入以下行:
$.get(this.href, null, function(data){ $(this).html(data); }, 'html');
I have already implemented some AJAX pagination in my Rails app by using the example code for the will_paginate plugin--which is apparently using Prototype.
But if I wanted to switch to using jQuery for future additions, I really don't want to have the Prototype stuff sitting around too (yes, I know it's possible). I haven't written a lick of JavaScript in years, let alone looked into Prototype and jQuery... so I could use some help converting this bit into jQuery-compatible syntax:
document.observe("dom:loaded", function() {
// the element in which we will observe all clicks and capture
// ones originating from pagination links
var container = $(document.body)
if (container) {
var img = new Image
img.src = '/images/spinner.gif'
function createSpinner() {
return new Element('img', { src: img.src, 'class': 'spinner' })
}
container.observe('click', function(e) {
var el = e.element()
if (el.match('.pagination a')) {
el.up('.pagination').insert(createSpinner())
new Ajax.Request(el.href, { method: 'get' })
e.stop()
}
})
}
})
Thanks in advance!
Edit: Nick Craver's answer got me 90% of the way there, so I just had to pick up enough jQuery to make the HTML element substitution. In place of the line where Nick had $.get($(this).attr("href"));
, put this line:
$.get(this.href, null, function(data){ $(this).html(data); }, 'html');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在 jQuery 中将其缩短为:
我不完全确定
new Ajax.Request(el.href, { method: 'get' })
不过,这是一个正在请求的脚本吗?返回后似乎没有对内容进行任何处理。You can shorten this down a bit in jQuery to:
I'm not entirely sure about
new Ajax.Request(el.href, { method: 'get' })
though, is this a script being requested? It looks like nothing's being done with the content after return.