1 回答
TA贡献1773条经验 获得超3个赞
我更改了您的 HTML 以使其有效 - 最好使用数据属性来存储体重、尺寸和人员等信息。此外,保持此解决方案动态更容易,因为它从所选选项中读取所有属性,并在属性名称以“data”开头的情况下附加它们的值。
$(document).ready(function() {
$('select.conditional-element-selector').on('change', function() {
var targetIndex = this.selectedIndex;
var selected = $(this).children("option:selected");
$(selected).each(function() {
$.each(this.attributes, function() {
if (this.name.startsWith("data")) {
var attrName = this.name.substr(5);
$('.conditional-element-' + targetIndex).find("." + attrName).text(this.value)
}
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="conditional-element-selector">
<option>Please select</option>
<option value="select-element-1" data-weight="12" data-size="20" data-persons="10">Option 1</option>
<option value="select-element-2" data-weight="24" data-size="40" data-persons="20">Option 2</option>
<option value="select-element-3" data-weight="48" data-size="80" data-persons="40">Option 3</option>
</select>
<div class="conditional-element-1">
<ul>
<li><span class="weight"></span> kg</li>
<li><span class="persons"></span></li>
<li><span class="size"></span> m3</li>
</ul>
</div>
<div class="conditional-element-2">
<ul>
<li><span class="weight"></span> kg</li>
<li><span class="persons"></span></li>
<li><span class="size"></span> m3</li>
</ul>
</div>
<div class="conditional-element-3">
<ul>
<li><span class="weight"></span> kg</li>
<li><span class="persons"></span></li>
<li><span class="size"></span> m3</li>
</ul>
</div>
- 1 回答
- 0 关注
- 87 浏览
添加回答
举报