javascript - 我想使用 jquery 打开链接

标签 javascript jquery

我想通过在更改功能中使用其 anchor ID 单击 anchor 来使用 Jquery 打开链接。请帮我打开它

<div id="div1" style="display:none">
    <a id="0" href="http://www.friferie.dk/inspiration/Belgien">Belgium</a>
    <a id="1" href="http://www.friferie.dk/inspiration/Bulgarien">Bulgarien</a>
    <a id="2" href="http://www.friferie.dk/inspiration/Danmark">Danmark</a>
 </div>


         **I want to pass id then open particular href into it**    

    $ ("").change(function  ()  { 
}

最佳答案

长版本(为了可读性):

$ ("#someselector").change(function  ()  { 
   // Get selected value
   var val = $(this).val();

   // Use the selected value to create a jQuery ID selector to get the link
   var link = $('#' + val);

   // get the href value
   var href = link.attr("href");

   // Change the browser location
   window.location = link;
});

或者模拟链接点击:

$ ("#someselector").change(function  ()  { 
   // Get selected value
   var val = $(this).val();

   // Use the selected value to create a jQuery ID selector and get the link
   var link = $('#' + val);

   // Click the link
   link[0].click();
});

我倾向于使用 [0].click() 而不是 jQuery click() ,因为它会影响底层浏览器实现(我们不会关心关于 jQuery 额外功能,因为页面会发生变化)。

注释:

  • 两个示例都可以缩短,例如通过删除局部变量,但这是为了解释目的

例如

$ ("#someselector").change(function  ()  { 
   window.location = $('#' + $(this).val()).attr("href");
});

$ ("#someselector").change(function  ()  { 
   $('#' + $(this).val())[0].click();    // Or `).click()` is you want it shorter
});

关于javascript - 我想使用 jquery 打开链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32326920/

相关文章:

javascript - HTML 表单在输入时运行 javascript?

jquery - 调用 jQuery 扩展中的方法

php - 我需要对 jquery 中选择框值的值求和

javascript - Chrome 10 : Custom Video Interface Problem

javascript - 从对象数组中添加/替换对象 JavaScript

javascript - JavaScript JIT 的显式控制?

javascript - AWS CDK 用户池授权者

javascript - IE6 上的 removeAttr/addClass 问题

javascript - 使用 jquery 设置动画时如何避免兄弟元素摇晃

javascript - 未处理的拒绝 ReferenceError : paginate is not defined