在这种情况下:
$.get($(this).attr('href'), function(destino){
//
}
如何读取从文件 $(this).attr('href') 获取的元素并将它们保存在变量中以供以后使用?
我尝试了这个选项,但没有任何效果:
1)
$titulo = $(destino).get('title');
$mensagem = $(destino).get('body');
2)
$titulo = destino.getElementByName('title');
$mensagem = destino.getElementByName('body');
3)
$titulo = destino.title;
$mensagem = destino.body;
4)
$titulo = $(destino).attr('title');
$mensagem = $(destino).attr('body');
我尝试这种方式并在句子末尾附加 .text() 和 .val() 。有人可以说这是怎么做到的吗?
更新
根据有关此主题的建议,我编写了以下代码:
$('document').ready(function(){
$('a').click(function(e){
if($(this).attr('href') != 'logout.html') {
e.preventDefault();
$.get($(this).attr('href'), function(destino){
var $destino = $(destino);
$titulo = $destino.find('title').text();
$mensagem = $destino.find('body').html();
alert('titulo = '+$titulo+' // mensagem = '+$mensagem)
BootstrapDialog.show({
title: $titulo,
message: $mensagem,
draggable: true
});
});
}
});
});
但不起作用。当我尝试查看 $titulo 和 $mensagem 的内容形式时,似乎两者分别是空的和未定义的。
另一个更新
我又做了一个改变。现在我有这个代码:
$('document').ready(function(){
$('a').click(function(e){
if($(this).attr('href') != 'logout.html') {
e.preventDefault();
$.get($(this).attr('href'), function(destino){
var $destino = $(destino);
$titulo = $destino.filter('title').text();
$mensagem = $destino.filter('body').html();
alert('titulo = '+$titulo+' // mensagem = '+$mensagem)
BootstrapDialog.show({
title: $titulo,
message: $mensagem,
draggable: true
});
});
}
});
});
$titulo 的值现在是正确的,但 $mensagem 的值不正确。
最佳答案
基本上,destino 只是一个字符串。您使用 JQuery 将其转换为带有 $(destino)
的 DOM 结构,因此该步骤无法避免。
对于初学者来说,您只想包装 destino 一次,因为 $(destino)
必须将整个下载转换为 DOM 结构。
例如
var $destino = $(destino)
因此您只需执行一次昂贵的操作。
然后 var $title = $destino.find('title')
和 var $body = $destino.find('body')
将引用您的元素想要。
如果您想要标题文本,则为$destino.find('title').text()
。如果您想要正文的 HTML,请使用 $destino.find('body').html()
如果你想要其他东西,你需要清楚你的意图,因为你提供了 4 种不获取数据的方法,但不知道你真正想要什么数据:)
关于jquery - 使用jquery读取存储在变量中的html元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22513909/