简体   繁体   English

添加属性在jQuery中不起作用

[英]Add attribute not working in jquery

I need to add an href attribute to a element using jqueny when window size is less than 768 pixel 我需要添加href属性a使用jqueny当窗口尺寸小于768象素元件

        <ul class="menu-link">
            <!--<li><a class="" href="#">HOME</a></li>-->
            <li><a id="#about-us" >ABOUT US</a></li>
            <li><a id="#contact" >CONTACT</a></li>
        </ul>

jQuery(document).ready(function ($) {
      var windowSize = $(window).width(); // 
            if (windowSize < 768) {
                //add attr
                $("#about-us").attr("href", "#about-us");
                $("#contact").attr("href", "#contact");
    }
});

It is not working for some reason am i doing something wrong 由于某种原因,它无法正常工作

to show what @pattmorter is pointing out 显示@pattmorter指出了什么

HTML: HTML:

<ul class="menu-link">
        <!--<li><a class="" href="#">HOME</a></li>-->

        <!-- remove the # from the ids -->
        <li><a id="about-us" >ABOUT US</a></li>
        <li><a id="contact" >CONTACT</a></li>
    </ul>

JS: JS:

jQuery(document).ready(function ($) {
  var windowSize = $(window).width(); // 
        if (windowSize < 768) {
            //add attr
            $("#about-us").attr("href", "#about-us");
            $("#contact").attr("href", "#contact");
        }
});

First of all you need to remove the # from the ids: 首先,您需要从ID中删除#

<li><a id="#about-us" >ABOUT US</a></li>
<li><a id="#contact" >CONTACT</a></li>

Should be 应该

<li><a id="about-us" >ABOUT US</a></li>
<li><a id=contact" >CONTACT</a></li>

Next, you probably want to run that on window.resize as well: 接下来,您可能还希望在window.resize上运行它:

$(function() {
  $(window).on('resize', function() {
    var add_remove = $(window).width() < 768; 
    $("#about-us").attr("href", add_remove ? "#about-us" : "");
    $("#contact").attr("href", add_remove ? "#contact" : "");
  });
  $(window).trigger('resize');
});

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

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