我想通过在更改功能中使用其 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/