更新选择列表以匹配URL上的标签更改(Update select list to match hashtag change on URL)

编程入门 行业动态 更新时间:2024-10-26 20:33:51
更新选择列表以匹配URL上的标签更改(Update select list to match hashtag change on URL)

我正在为商店的产品页面工作,能够预览多个图像。 截至目前,正在查看的当前图像更新了URL上的#hashtag。 我有一个选择列表,每个选项都标有一个匹配每个潜在主题标签的类。

我有一个开始,但只是不太确定如何使用jQuery来获取主题标签,将其与类匹配并执行某些操作。 触发点击或只是将选项更新为“已选择”会更好吗?

这是我的开始,不太清楚为什么它不起作用。

https://jsfiddle.net/ykmgzyc7/

var url = window.location.href;
var hash = url.substring(url.indexOf('#'));                          
$('option.' + hash).trigger('click'); 
  
 

I'm working on a product page for a store with the ability to preview multiple images. As of right now the current image being viewed updates the # hashtag on the URL. I have a select list with each option that is tagged with a class matching each potential hashtag.

I got a start, but just not quite sure how to use jQuery to take the hashtag, match it with a class and do something. Would it be better to trigger a click or simply update the option to 'selected'?

Here is my start, not quite sure why it's not working.

https://jsfiddle.net/ykmgzyc7/

var url = window.location.href;
var hash = url.substring(url.indexOf('#'));                          
$('option.' + hash).trigger('click'); 
  
 

最满意答案

由于您实际上并未加载新页面而只是使用锚点,因此可以使用jquery动态修改选择。

HTML:

<ul> <li><a href="#one">One</a></li> <li><a href="#two">Two</a></li> <li><a href="#three">Three</a></li> </ul> <select id="selectOptions"> <option class="one">One</option> <option class="two">Two</option> <option class="three">Three</option> </select>

jQuery的:

$("a").on("click",function(){ var link=$(this).attr('href'); var hash = link.substring(link.indexOf('#')+1); $('#selectOptions option').removeAttr('selected'); $('#selectOptions .'+hash).attr('selected',true); });

https://jsfiddle.net/ykmgzyc7/3/

Since you aren't actually loading a new page and just using the anchors you can dynamically modify the selection with jquery.

HTML:

<ul> <li><a href="#one">One</a></li> <li><a href="#two">Two</a></li> <li><a href="#three">Three</a></li> </ul> <select id="selectOptions"> <option class="one">One</option> <option class="two">Two</option> <option class="three">Three</option> </select>

Jquery:

$("a").on("click",function(){ var link=$(this).attr('href'); var hash = link.substring(link.indexOf('#')+1); $('#selectOptions option').removeAttr('selected'); $('#selectOptions .'+hash).attr('selected',true); });

https://jsfiddle.net/ykmgzyc7/3/

更多推荐

hashtag,URL,hash,更新,电脑培训,计算机培训,IT培训"/> <meta name="descripti

本文发布于:2023-04-28 01:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329632.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标签   列表   Update   select   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!