简体   繁体   English

如何使用 Jquery 获得选择的选项来更改链接的 href?

[英]How to get a selected option to change the href of a link using Jquery?

I'm trying to get a link to change when an option is selected using the code below, it works when I add the class to the select tag but not too the option tag.当我使用下面的代码选择一个选项时,我正在尝试获取一个更改链接,当我将 class 添加到 select 标签但不是选项标签时,它可以工作。 I think its probably a typo but not sure?我认为这可能是一个错字,但不确定?

<script>

$(document).ready(function(){
  $(".pickau").click(function(){
    $("#trigger").attr("href", "https://www.location.com.au");
  });
});

$(document).ready(function(){
  $(".picknz").click(function(){
    $("#trigger").attr("href", "https://www.location.co.nz");
  });
});

</script> 

And my dropdown and the link I'm trying to change based on the location selected:我的下拉列表和我试图根据所选位置更改的链接:

<label>What Country Are You In? (required)</label>
<select>
<option class="picknz">New Zealand</option>
<option class="pickau">Australia</option>
</select>  

<a href="http://www.location.co.nz/" id="trigger"><p>Location Link</p></a>

<p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>

click event on option is invalid (In javascript too) option上的click事件无效(也在 javascript 中)

Use change event on select , also you can get value directly from option dynamicallyselect上使用change事件,您也可以直接从option中动态获取值

One more thing, only one $(document).ready function is enough.还有一件事,只需一个$(document).ready function 就足够了。 You can wrap all of your code in that function您可以将所有代码包装在 function

 $(document).ready(function(){ $("#mySelect").change(function(evt){ $("#trigger").attr("href", evt.target.value); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label>What Country Are You In? (required)</label> <select id="mySelect"> <option value="https://www.location.co.nz">New Zealand</option> <option value="https://www.location.com.au">Australia</option> </select> <a href="http://www.location.co.nz/" id="trigger"><p>Location Link</p></a> <p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>

Update If the second link is fixed as /help , then you can do something like更新如果第二个链接固定为/help ,那么您可以执行类似的操作

<a href="http://www.location.co.nz/help" id="triggerHelp"><p>Location Link</p></a>

$("#mySelect").change(function(evt){
 $("#trigger").attr("href", evt.target.value);
 $("#triggerHelp").attr("href", evt.target.value + '/help');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM