通过选择的选项更改div的值

时间:2019-11-26 22:01:24

标签: javascript html

我必须编写一些代码,其中select包含三个选项,并且div的值将在更改后更改为所选项目的值,我尝试了很多方法和功能,但没有任何效果。这是我当前的代码:

$('select[class="country"]').on('change', function () {
    var get = $('select option:selected').text();
    $('#fDiv').text = get;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>The coolest country</h1>
<select name="country"id="country" class="country">
  <option value="Korea">Korea</option>
  <option value="China">China</option>
  <option value="Romania">Romania</option>
</select>
<div id="fDiv"></div>

请分享有关此代码可能存在问题的任何想法。

4 个答案:

答案 0 :(得分:1)

使用// Invalid TS code example of the relationship type BrandedHandlerDictionary = { <T extends HandlerVariant>[id: Id<T>]: T; } 就像:.text()

$('#fDiv').text(myText);
$('select[class="country"]').on('change', function() {
  var myText = $('select option:selected').text();
  $('#fDiv').text(myText);
});

答案 1 :(得分:1)

使用jQuery时,您无需使用工作分配=,而是将其用作('#id')。text(get):

$('select[class="country"]').on('change', function() {
  var get = $('select option:selected').val();
  $('#fDiv').text(get);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>The coolest country</h1>
<select name="country" id="country" class="country">
  <option value="Korea">Korea</option>
  <option value="China">China</option>
  <option value="Romania">Romania</option>

</select>
<div id="fDiv"></div>

答案 2 :(得分:0)

这是解决您问题的纯JavaScript方法。

const select = document.querySelector('#country');
const div = document.querySelector('#fDiv');
div.innerHTML = select.selectedOptions[0].value // remove this if you dont want a value set initially
select.addEventListener('change', (event) => {
   div.innerHTML = select.selectedOptions[0].value
});
<h1>The coolest country</h1>
<select name="country"id="country" class="country">
  <option value="Korea">Korea</option>
  <option value="China">China</option>
  <option value="Romania">Romania</option>
</select>
<div id="fDiv"></div>

答案 3 :(得分:0)

1)在文件开头添加<html>

2)在name = "country" id="country"

之间添加一个空格

3)使用带参数的text():例如$('#fDiv').text(get);

  $('select[class="country"]').on('change', function () {
  var get = $('select option:selected').text();
  $('#fDiv').text(get);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Cool Site</title>

</head>
<body>

<h1>The coolest country</h1>
<select name="country" id="country" class="country">
<option value="Korea">Korea</option>
<option value="China">China</option>
<option value="Romania">Romania</option>
</select>
<div id="fDiv"></div>


</body>
</html>