如何从“this”对象获取html数据-香草JavaScript
我正在尝试重做一个只使用vanilla js处理jQuery的函数。我似乎不知道如何从这个对象获取所需的数据。我需要获取parentid数据属性的值,但我尝试过的任何方法都不起作用 在我的职责范围内,如果我包括 console.logthis 我得到输出:如何从“this”对象获取html数据-香草JavaScript,javascript,html,dom,Javascript,Html,Dom,我正在尝试重做一个只使用vanilla js处理jQuery的函数。我似乎不知道如何从这个对象获取所需的数据。我需要获取parentid数据属性的值,但我尝试过的任何方法都不起作用 在我的职责范围内,如果我包括 console.logthis 我得到输出: <a href="javascript:;" data-parentid="1" data-groupingtype="2">Text Content</a> HTML: <div id="selectionC
<a href="javascript:;" data-parentid="1" data-groupingtype="2">Text Content</a>
HTML:
<div id="selectionContainer" class="form-group">
<button id="selectionButton" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"><span>Select Grouping</span> <span class="caret"></span></button>
<ul id="selectionList" class="dropdown-menu" role="menu">
<li><a href="javascript:;" data-parentid="11" data-type="1">Option 1</a></li>
<li><a href="javascript:;" data-parentid="11" data-type="2">Option 2</a></li>
<li><a href="javascript:;" data-parentid="11" data-type="3">Option 3</a></li>
<li class="divider"></li>
<li><a href="javascript:;" data-parentid="12" data-type="1">Alternate 1</a></li>
<li><a href="javascript:;" data-parentid="12" data-type="2">Alternate 2</a></li>
<li><a href="javascript:;" data-parentid="12" data-type="3">Alternate 3</a></li>
</ul>
</div>
如果有人能给我指出正确的方向,我会非常感激 如果您有一个项目,其中包含数据foo=bar,那么您可以通过
foo.getAttribute("data-foo")
数据函数是一个jQuery函数,不适用于Vanilla JS。随后,您将需要使用
this.getAttribute("data-parentid")
这里有一些您可以做的更改 而不是做 document.queryselectorselection按钮span:first-child.textContent 你能行 让getButtonSpan=document.getElementById'selectionButton'.firstElementChild 这将使用id selectionButton提供此dom元素中的第一个子元素 您可以使用forEach,尽管传统的for循环同样好。使用forEach的参数获取锚定标记dom&向其添加事件侦听器。单击它时,使用innerHTML获取文本并将其设置为按钮的第一个子项 除了getAttribute之外,还可以使用它从dom检索数据属性 在替换jquery的代码中,您使用的$this.dataparentid违反了您的目标 让getButtonSpan=document.getElementById'selectionButton'.firstElementChild; document.getElementById'selectionList'.querySelectorAll'a'.forEachfunctionitem{ item.addEventListener“单击”函数{ getButtonSpan.innerHTML=item.innerHTML; 让selectedParentID=item.dataset.parentid; 让selectedType=item.dataset.type; 如果选择了ParentId&&selectedType{ doSomeThingselectedParentID,selectedType; } } } 函数doSomeThinga,b{ console.log`selectedParentID:${a}&selectedType:${b}` } 选择分组
请分享完整的html
foo.getAttribute("data-foo")
this.getAttribute("data-parentid")