猿问

无法读取未定义的属性“setAttribute”

我正在尝试使用以下代码创建手风琴。如果将以下标签放在一起,则其工作正常。我想在页面其他部分的某个标签内插入元素


     <dt>

     <li class="nav-item"   id='l1' >

     <a class="nav-link active js-accordionTrigger"   href="#accordion1" aria-expanded="false" aria- 

     controls="accordion1">

     <i class="material-icons">camera</i>

      Studio

      </a>

      </li></dt>


        <dd class="accordion-content accordionItem is-collapsed" id="accordion1" aria-hidden="true">

            <p>Lorem ipsum doplacerat. Cras justo purus,enim sit amet varius. Pellentesque justo dui, 

          sodales quis luctus a, iaculis eget mauris.</p>

           </dd> 

如果我尝试在这里放置标签。它不起作用,我可以看到错误 setAttribute undefined


         <div class="tab-content tab-space">

        <div class="tab-pane active text-center gallery" >

         <dd class="accordion-content accordionItem is-collapsed" id="accordion1" aria-hidden="true">

            <p>Lorem iet mauris.</p>

           </dd> 

         </div>

        </div>

                        

这是Javascript和Jquery代码


   <script>

   $(document).ready(function () {


  var d = document,

    $accordionToggles = $('.js-accordionTrigger'),

    touchSupported = ('ontouchstart' in window),

    pointerSupported = ('pointerdown' in window),


    skipClickDelay = function (e) {

        e.preventDefault();

        e.target.click();

    },


    setAriaAttr = function (el, ariaType, newProperty) {

        el[0].setAttribute(ariaType, newProperty);

    },


    setAccordionAria = function (el1, el2, expanded) {

        setAriaAttr(el1, 'aria-expanded', expanded ? true : false);

        setAriaAttr(el2, 'aria-expanded', expanded ? false : true);

    },


繁星coding
浏览 181回答 1
1回答

素胚勾勒不出你

设置属性https://api.jquery.com/attr/有attratjquery 方法。同样var $currQuestion = $accordionToggles.eq(i), $currAnswer = $currQuestion.closest('dt').next('dd')在这里,您将问题声明为单个元素,并将答案作为数组,因此您必须添加eq(0)到$currQuestion.closest('dt').next('dd'),或者遍历所有 el2 项目以设置属性。当您包装dd到其他标签divs时,jquerynext()无法在dt附近找到,因此您$currAnswer的未定义,您必须使用$currQuestion.closest('dt').next('.tab-content.tab-space').find('dd')解决方案:&nbsp; &nbsp; setAriaAttr = function (el, ariaType, newProperty) {&nbsp; &nbsp; &nbsp; &nbsp; el.attr(ariaType, newProperty);&nbsp; &nbsp; },&nbsp; &nbsp; setAccordionAria = function (el1, el2, expanded) {&nbsp; &nbsp; &nbsp; &nbsp; setAriaAttr(el1, 'aria-expanded', expanded);&nbsp; &nbsp; &nbsp; &nbsp; setAriaAttr(el2, 'aria-expanded', !expanded);&nbsp; &nbsp; },...&nbsp; &nbsp; &nbsp; &nbsp; for (var i = 0; i < $accordionToggles.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var $currQuestion = $accordionToggles.eq(i),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $currAnswer = $currQuestion.closest('dt').next('.tab-content.tab-space').find('dd').eq(0);工作小提琴https://jsfiddle.net/w7gpLrse/
随时随地看视频慕课网APP
我要回答