我尝试了在这里和其他地方找到的东西,但似乎卡住了。这里就是我想要做的:点击链接应该通过jQuery更改标题属性ajax.get调用
- 拨动它的父元素类
- 通过GET发送一个Ajax请求与链接的id和标题和标题更改为响应
我想到了#1,并且能够在#2发送ajax请求(并执行任何被调用的文件应该做的事情,它的响应也很好),但我很努力地将响应附加到标题上。
这里是我的HTML代码
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('li div.toggle a').click(function() {
$.get(
"test1.php",
{ id: $(this).attr('id'), title: $(this).attr('title') },
function(data) {
$.title = data;
},
"text");
$(this).attr('title', $.title);
$(this).closest('li').toggleClass('highlight');
});
});
</script>
<style type="text/css" media="screen">
.highlight {
background: red;
}
</style>
</head>
<body>
<ul>
<li>
<div>1</div>
<div class="toggle"><a href="#" id="1" title="this is off">Toggle</a></div>
</li>
<li class="highlight">
<div>2</div>
<div class="toggle"><a href="#" id="2" title="this is on">Toggle</a></div>
</li>
</ul>
</body>
</html>
我想,而不是$.title = data;
直接使用$(this).attr('title', data);
但不工作 - 我的猜测是,$(this)
在脚本中的那个阶段是不<a>
标签,但我不知道足够的jQuery来了解如何以不同方式“挑选”正确的<a>
标记。无论如何,奇怪的是,它是这样工作的 - 但只是每隔一段时间!所以点击改变类,但没有标题,接下来点击再次,现在还标题更改类...
我然后通过其ID调用<a>
元素尝试过了,我硬编码它 - 那么它每次都有效:$('#1').attr('title', data);
,但当然我需要使用正确的ID取决于哪个链接被点击 - 但我不知道如何在这里得到它。
这里是被称为
<?php
if (substr($_GET['title'], -2)=="on") {
$result = "off";
}
else {
$result = "on";
}
print "this is ".$result;
?>
我的猜测文件的test1.php代码是我不完全了解的jQuery和我只是失去了一些东西很简单/基本在这里。预先感谢您的期待。 j)。
j。
请注意,安迪建议下面基本上相同的东西,用更少的话。他将改变title属性的代码移动到回调函数中。无论您是希望将重点业务留在同步代码还是将其移入成功回调,都取决于您希望执行的时间。 – alegscogs 2011-01-23 15:30:54