如何用不同的<a href="">

how to call jquery function with different <a href="">

本文关键字:quot href gt lt 何用不      更新时间:2023-09-26

我想调用两个不同的jquery函数来隐藏链接

<a href="">.zip file, first link
</a>
<script>
$("a").click(function() {
location.href="first.location";
return false;
});
</script>
<a href="">.tar.gz file, second link
</a>
 <script>
 $("a").click(function() {
 location.href=="second.location";
 return false;
 });
 </script>

如何调用这两个函数,以便调用单击第一个链接的第一个函数和单击第二个链接的第二个函数?

感谢lo

这不是最好的解决方案。为了获得最佳效果,您可能需要重新构造html,并向链接或其父级添加某种类和ID来识别它们。但这将工作

对于第一个链路

$("a:eq(0)").click(function() {
location.href="first.location";
return false;
});

并且对于第二链路

 $("a:eq(1)").click(function() {
 location.href=="second.location";
 return false;
 });

如果在标记中设置href,则不需要JQueryJavascript

<a href="first.location">.zip file, first link
</a>
<a href="second.location">.tar.gz file, second link
</a>

您可以在此处使用:eq()选择器,如:

// Clicking the first link
$("a:eq(0)").click(function () {
    location.href = "first.location";
    return false;
});
// Clicking the second link
$("a:eq(1)").click(function () {
    location.href = "second.location";
    return false;
});

就像已经有人建议的那样,最好的方法是为这些a标记使用不同的id。但是,如果出于某种原因你不想分配id(你到底为什么要这样做?)你可以做以下事情:

将锚标签包装在div中,并给它一个类似的id

 <div id="myDiv">
  <a href="#">First Link</a>
  <a href="#">Second Div</a>
 </div >

然后使用jQuery进行链接:

<script>
 $(function(){
   $("myDiv").children(a:first-child).click(function(){
      // Do stuff here
   });
   $("myDiv").children(a:last-child).click(function(){
      // Do stuff here
   });
 });
</script>

您可以在链接中引入一个id属性。然后基于元素的id触发事件。

<a href="" id='link1'>.zip file, first link
</a>
<script>
$("#link1").click(function() {
location.href="first.location";
return false;
});
</script>
<a href="" id='link2'>.tar.gz file, second link
</a>
 <script>
 $("#link2").click(function() {
 location.href=="second.location";
 return false;
 });
 </script>

在html(href)中提供链接

$("a").click(function()
{
    location.href = $(this).attr('href');
    return false;
});

我认为这可能会有所帮助:

<a id="first" href="">.zip file, first link</a>
<script>
  $("first").click(function() {
    location.href="first.location";
    return false;
  });
</script>
<a id="second" href="">.tar.gz file, second link </a>
<script>
  $("second").click(function() {
    location.href=="second.location";
    return false;
  });
</script>

$("a:eq(0)").click(function() { location.href="first.location"; return false; });

$("a:eq(1)").click(function() { location.href=="second.location"; return false; });