如何根据语义UI的下拉菜单中的所选项目更改页面上的文本?

时间:2019-06-26 02:20:23

标签: javascript html semantic-ui

从语义UI的下拉菜单中选择一个项目时,尝试在页面上的两个div标签中自动更改文本时遇到麻烦。我不确定我要去哪里。我做了一个javascript函数,该函数应该以下拉列表为目标并从那里检索值。

这是HTML代码

<h2 class="sTypeText">Undefined</h2>
<span class="annotation">
  You've selected <b class="sTypeText">undefined</b> mode. You can continually edit this mode and its details.
</span>

<div id="dropdown" class="ui fluid selection dropdown" onchange="changeSelect">
  <div class="text">Choose Type</div>
  <i class="dropdown icon"></i>
  <div class="menu">
    <div class="item" data-value="A">Assessment</div>
    <div class="item" data-value="G">Group</div>
    <div class="item" data-value="S">Solo</div>
  </div>
</div>

这是Javascript代码:

function changeSelect() {
    if (document.getElementById("dropdown").data-value == "A") {
        document.getElementByClassName("sTypeText").innerHTML = "Assessment";
    } else if (document.getElementById("dropdown").data-value == "G") {
        document.getElementByClassName("sTypeText").innerHTML = "Group"; 
    } else if (document.getElementById("dropdown").data-value == "S") {
        document.getElementByClassName("sTypeText").innerHTML = "Solo";
    }
}

1 个答案:

答案 0 :(得分:0)

要获取数据属性值,可以尝试使用{DOMElement}.getAttribute('data-{name of attribute}')或使用dataset属性:{DOMElement}.dataset.{name of attribute}

尝试将代码更改为此,以从数据属性“值”获取值:

function changeSelect() {
    if (document.getElementByClassName("dropdown").dataset.value == "A") {
        document.getElementByClassName("sTypeText").innerHTML = "Assessment";
    } else if (document.getElementById("dropdown").dataset.value == "G") {
        document.getElementByClassName("sTypeText").innerHTML = "Group"; 
    } else if (document.getElementById("dropdown").dataset.value == "S") {
        document.getElementByClassName("sTypeText").innerHTML = "Solo";
    }
}