修改后的问题(原文见下文):
这是一个简单的 ajax 加载示例,在加载的内容中的元素上具有事件绑定:
soTest.htm
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript" type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script>
function changeBG(obj)
{
alert('Color 1: Should Turn Red');
jQuery(obj).css('background-color','red');
alert('Color 2: Should Turn Green');
jQuery('#' + jQuery(obj).attr('id')).css('background-color','green');
}
jQuery(document).ready(
function() {
jQuery('.loadedContent').load('soTest2.htm');
jQuery('body').delegate("#theElem","click",
function(){
var obj = this;
jQuery('.loadedContent').load('soTest2.htm',
function(){
changeBG(obj);
}
);
});
}
);
</script>
</head>
<body>
<div class="loadedContent">
</div>
</body>
</html>
Ajax加载的内容,soTest2.htm:
<div id="theElem" >
Hello
</div>
那么为什么这不起作用:
jQuery(obj).css('background-color','red');
但这确实:
jQuery('#' + jQuery(obj).attr('id')).css('background-color','red');
++++++++++原始问题:++++++++++
我有一个表格,当单击特定表格标题(具有“排序”类的标题)时,我想对其进行排序。
例如:
<a href="##" class="sort" sortby="LOCATION" direction="asc">Location</a>
为此,我有以下代码:
jQuery('body').delegate("click", ".sort", function(event) {
event.preventDefault();
jQuery('.searchResults').html('<div align="center" style="margin-top:35px;"><img src="/common/images/ajax-loader_big.gif" /></div>');
var TimeStamp = new Date().getTime();
var sortItem = this;
jQuery('.searchResults').load('modules/configSearchResultsOutput.cfm?' + TimeStamp + '&sortby=' + jQuery(this).attr('sortby') + '&direction=' + jQuery(this).attr('direction'), {
data: jQuery('#results').val()
}, function() {
sortCallback(sortItem);
});
});
因此,在这些可排序列标题之一的单击事件中,我将整个“this”范围存储在 var 中以传递给该函数。
为了简化问题,我只想说我们正在尝试根据我正在使用的自定义 attr 'direction' 更改单击元素的背景颜色:
function sortCallback(obj) {
//Returns correct attribute value
alert('In Callback: ' + jQuery(obj).attr('direction'));
//Does not return correct attribute value -- almost like it's cached or something
alert('Long hand reference: ' + jQuery('.sort[sortby="' + jQuery(obj).attr('sortby') + '"]').attr('direction'));
//Must reference value via (obj) to get correct updated value
if (jQuery(obj).attr('direction') == 'asc') {
//Changing a value within the element via this longhand approach works
jQuery('.sort[sortby="' + jQuery(obj).attr('sortby') + '"]').css('background-color', 'red');
//Changing a value within the element via this shorter approach does not work
jQuery(obj).css('background-color', 'red');
}
else {
//Works
jQuery('.sort[sortby="' + jQuery(obj).attr('sortby') + '"]').css('background-color', 'green');
//Doesn't work
jQuery(obj).css('background-color', 'green');
}
}
我假设我不了解 javascript 范围的某些方面(理解“this”对我来说非常难以捉摸)。
问题总结:
如果我将一个 var'd 'this' 范围传递给一个函数,为什么我不能更改 'this' 元素的各个方面,为什么我必须使用很长的方法来更改它们?
对我来说是一个棘手的问题,希望我做得足够好。
谢谢!