首页 > 解决方案 > 如何专门从 jquery 中的 select 标记更改 innerHTML 值?

问题描述

我正在编写代码以允许用户在该域上创建自定义。正如您在下面的示例中看到的,用户可以选择example.com并通过从下面的选择标签中进行选择将其更改为任何example(n).com域。

我想要实现的是,当我选择example1.comexample3.com时,http://将变为https://

例子:

当我从选择列表中选择 example1.com 时,输出将是

https://example1.com _

https://example3.com _

但如果我选择example2.com / example4.com,它将保持原样。

http://example2.com _

http://example4.com _

我正在尝试在 jquery 中实现它。任何帮助和建议将不胜感激。

function changeText(url)
  {
  document.getElementById('mydiv').innerHTML = url;
  }
<div>http://<span id='mydiv'>example0.com</span></div>

<select onchange='changeText(this.value)'>
  <option>example1.com</option>
  <option>example2.com</option>
  <option>example3.com</option>
  <option>example4.com</option>
</select>

标签: javascriptjquery

解决方案


看看这个片段。

function changeText(urlPostFixNumber) {
    var protocol;
    var url;
    var domain = '://example' + urlPostFixNumber + '.com';

    switch(urlPostFixNumber) {
        case "1":
        case "3":
            protocol = 'https';
            break;
        default:
            protocol = 'http';
    }

    url = protocol + domain;
    document.getElementById('mydiv').textContent = url;
}
<p id="mydiv">http://example0.com</p>

<select onchange="changeText(this.value)">
  <option value="0" selected>example0.com</option>
  <option value="1">example1.com</option>
  <option value="2">example2.com</option>
  <option value="3">example3.com</option>
  <option value="4">example4.com</option>
</select>


推荐阅读