我有一个脚本,需要设置两个json数据调用url中的一个,这取决于单击哪个元素来调用查询。
我如何编码url:属性,使其由哪个元素被点击确定?
在我的脑海中,我想创建一个隐藏的输入字段,并设置一个标志,我可以根据点击的链接读/写。然后我可以用if/Then
包装url:参数然而,我记得jQuery有一个each()方法,我可能可以使用。
有什么建议吗?
代码:<div id='items'>
Label:
<a href='#' id='item1'>Item 1</a>
<a href='#' id='item2'>Item 2</a>
</div>
jQuery("#items").find("a").each.click(function(){
jQuery.ajax({contentType: "application/json; charset=utf-8",dataType: "json",
if(jQuery(this).id = '#item1')
{
url: "first url"
}
else
{
url: "second url"
}
});
if(this.id == 'item1')
var url = "first url";
else
var url = "second url";
,然后像这样使用:
{ url: $url }
至于链接,我建议:
$.ajax({
type: 'GET',
url: $(this).attr('href'),
success: function(data) {
...
},
});
:当我们进行ajax调用并等待响应并阻塞页面时显示一个旋转器
可以使用条件运算符:
url: this.id == 'item1' ? "first" : "second",
你可以使用一个属性:
<div id='items'>
Label:
<a href='#' id='item1' data-url="page1.html">Item 1</a>
<a href='#' id='item2' data-url="page2.html">Item 2</a>
</div>
然后使用jQuery的data()函数来检索。
jQuery('#items a').click(function(){
jQuery.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
url: $(this).data("url")
});
});
既然你正在使用锚,我建议给锚适当的url,然后有jQuery获取$(this).attr('href')
只需在运行时切换:
<a href="http://www.google.com/" class="link">Item 1</a>
<a href="http://www.bing.com/" class="link">Item 2</a>
然后你的脚本看起来像这样:
$('.link').each(function()
{
var currentHref = this.href;
// Unset the value so when people click on it, they dont leave the page
// jQuery 1.6
$(this).prop('href', '#');
// Other Versions
$(this).attr('href', '#');
$(this).click(function()
{
// Do Ajax Call. The URL of the link is contained within `currentHref` which is contained in this scope via closure.
});
});
这样,javascript只是在运行时重新排列链接中包含的数据。