Javascript 用jquery获取标题
当点击时,我试图抓住Javascript 用jquery获取标题,javascript,jquery,Javascript,Jquery,当点击时,我试图抓住上的“标题”。它不断返回未定义的值 html “这个”可能不是李安。或者浏览器有错误(即?)。你的代码对我来说似乎是正确的 “这”可能不是李。或者浏览器有错误(即?)。你的代码对我来说似乎是正确的 这样不行吗 $('li').click(function(){ alert($(this).attr('title')); }); 这不管用 $('li').click(function(){ alert($(this).attr('title')); });
上的“标题”。它不断返回未定义的值
html
“这个”可能不是李安。或者浏览器有错误(即?)。你的代码对我来说似乎是正确的 “这”可能不是李。或者浏览器有错误(即?)。你的代码对我来说似乎是正确的 这样不行吗
$('li').click(function(){
alert($(this).attr('title'));
});
这不管用
$('li').click(function(){
alert($(this).attr('title'));
});
如何将单击处理程序附加到
li
元素上?您确定处理程序中的这个正在指向li
元素吗
我会尝试记录这个
,并找出它指向什么
如果this
指向li
,那么$(this.attr('title')
应该可以很好地工作。如何将单击处理程序附加到li
元素上?您确定处理程序中的这个正在指向li
元素吗
我会尝试记录这个
,并找出它指向什么
如果this
指向li
,那么$(this.attr('title')
应该可以很好地工作。您应该在单击的li
元素上创建一个闭包。您将在click handler函数的另一个函数中获得此
,因此此
的定义将不同于原始函数
$('.navigation li').click(function () {
// cache the element here
var that = $(this);
$('.slider').animate({
marginLeft: 0
}, 500, function() {
// then access that instead here
// (we're creating a closure on the that variable)
var test = that.attr('title');
alert(test);
location.href = '';
});
});
如果有两个嵌套函数,它们的this
变量将不同:
function foo () {
// this here ...
function bar () {
// ... is different from this here
}
}
所以在此基础上
$('li').click(function () {
// $(this) here ...
$('something').slider({},100, function () {
// ... is different from $(this) here
});
});
您应该在单击的li
元素上创建一个闭包。您将在click handler函数的另一个函数中获得此
,因此此
的定义将不同于原始函数
$('.navigation li').click(function () {
// cache the element here
var that = $(this);
$('.slider').animate({
marginLeft: 0
}, 500, function() {
// then access that instead here
// (we're creating a closure on the that variable)
var test = that.attr('title');
alert(test);
location.href = '';
});
});
如果有两个嵌套函数,它们的this
变量将不同:
function foo () {
// this here ...
function bar () {
// ... is different from this here
}
}
所以在此基础上
$('li').click(function () {
// $(this) here ...
$('something').slider({},100, function () {
// ... is different from $(this) here
});
});
我猜会是:
$("li.clickMe").click(function () {
$("this").attr("title").whateverYouNeedToDo("");
});
我猜会是:
$("li.clickMe").click(function () {
$("this").attr("title").whateverYouNeedToDo("");
});
尝试.prop(“title”)
而不是.attr(“title”)
,但我认为它无论如何都应该起作用……你确定“this”实际上是“li”元素吗?也许可以尝试将其记录到控制台中?您能向我们展示一下$(this)
)的上下文吗?似乎工作正常-尝试添加警报(this.tagName)
,以了解您当前使用的标记。如果不是LI
,那么您的事件处理程序有问题,我们需要查看更多代码。如果是,那么您有其他干扰,我们需要查看更多代码。请尝试.prop(“title”)
而不是.attr(“title”)
,但我认为它无论如何都应该工作……您确定“this”实际上是“li”元素吗?也许可以尝试将其记录到控制台中?您能向我们展示一下$(this)
)的上下文吗?似乎工作正常-尝试添加警报(this.tagName)
,以了解您当前使用的标记。如果不是LI
,那么您的事件处理程序有问题,我们需要查看更多代码。如果是的话,那么你有其他干扰,我们需要看到更多的代码。它在FF和chromeits中这样做