根据选择选项修改元素

Modify element based on select option

本文关键字:修改 元素 选项 选择      更新时间:2023-09-26

嗨,我一直在互联网上搜索(不仅仅是堆栈溢出),但我无法直接找到答案。也许这就是我搜索的方式?但在这里,我有一个选择 HTMl 元素(如下例所示)。我正在尝试使用 jquery(除非有更好的方法)根据选择中的选择来更新我网站上的段落部分。

例。

<select id ="work">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<p id="updatedparagraph">
updated text here.
updated text here.
updated text here
</p>

默认情况下,它应该以 A 开头,因此段落部分中的文本设置为默认值。但是,如果选择下拉列表并将其设置为 B 或 C,我希望文本根据选择的内容而更改。关于如何正确完成此操作的任何想法?

基于 OP 的注释,以便根据下拉列表中的值显示相应的段落部分。

<select id ="work">
<option value="updatedparagraph">a</option>
<option value="updatedparagraph1">b</option>
<option value="updatedparagraph2">c</option>
</select>
<p id="updatedparagraph">
history will go.
history will go.
history will go.
history will go.
</p>
<p id="updatedparagraph1">
history will not  go.
history will not go.
history will not go.
history will not go.
</p>
<p id="updatedparagraph2">
history will never go.
history will never go.
history will never go.
history will never go.
</p> 

 <script>
    $(document).ready(function(){
    $('#work').change(function()
    {
      $('[id^=updatedparagraph]').hide();  // hide all paragraph tag that starts with id = updatedparagraph
      $('#' + this.value).show(); // extract the value from the dropdown , locate that paragraph with id = value and show it.
    }).change();  // trigger change event as soon as the dropdown is loaded - optional.

});
</script>

例 : http://jsfiddle.net/DinoMyte/X6jzs/31/

如果您希望将特定文本动态插入到单个段落字段中,则可以创建具有键值对的对象。

var obj = {'a': 'Hello a', 'b': 'Hello b','c': 'Hello c'};
$('#work').change(function()
{
  $('#updatedparagraph').text(obj[this.value]);
}).change();

例 : http://jsfiddle.net/DinoMyte/X6jzs/42/