我如何连接 select 和输入字段的值,并与 JavaScript 一起显示

How do i concat the values of select and input field and also display altogether with JavaScript

我正在制作一个 phone 选择器输入菜单,其中有一个 <select><input> 字段,如下所示:

<select id="country">
    <option data-countryCode="IN" value="91">India</option>
    <option data-countryCode="US" value="1">US</option>
    <option data-countryCode="GB" value="44">UK</option>
</select>


<input type="tel" placeholder ="956 826 4457" id="tel">

JS代码:

 const select = document.querySelector('#country');
    const tel = document.getElementById('tel')
        tel.value = `${select.options[select.selectedIndex].value}` +`${tel.value}`


如何将 concat/join select 值与 input 字段一起显示在该输入字段中。

问题是您在第一行放了一个“-”而不是“=”。应该是:

<select id="country">

还有,你为什么用jQuery? Javascript 涵盖它同样容易:

const select = document.getElementById('country');
const tel = document.getElementById('tel');
tel.value = select.options[select.selectedIndex].value + tel.value;

首先,您提供的代码中有一些奇怪的细节。

<select id-"country"> 

应该是

<select id="country">

?

  1. 为什么concat模板和plus同时使用模板?仅仅使用

    还不够吗

    tel.value = ${select.options[select.selectedIndex].value}${tel.value}

?

另外,你打算用什么事件?如果我们 select 国家/地区第一次运行良好,例如添加“91”。但下次(如果我们不小心选错了国家)它会重新添加代码。

关于这个问题,你能不能更详细的解释一下现在到底发生了什么

你可以这样做

const select = document.querySelector('#country');
const tel = document.getElementById('tel');
let prevVal = select.value; // storing previous value of select

// this block will be exected on init of code
if(tel.value) tel.value = `${select.value}${tel.value}`;
else tel.placeholder = `${select.value}${tel.placeholder}`;

// adding event on changing input
tel.addEventListener('change', ({ target }) => {
  const reg = new RegExp(`(^${prevVal} )`);
  // checking do we already have country code
  if (reg.test(target.value)) tel.value = tel.value.replace(reg, target.value);
  else tel.value = `${select.value}${target.value}`;
});

// adding event on changing select
select.addEventListener('change', ({ target }) => {
  const reg = new RegExp(`(^${prevVal})`);
  if(tel.value) tel.value = `${target.value}${tel.value.replace(reg, '')}`;
  else tel.placeholder =  tel.placeholder.replace(reg, target.value);
  prevVal = target.value;
});
<select id="country">
    <option data-countryCode="IN" value="91" selected>India</option>
    <option data-countryCode="US" value="1">US</option>
    <option data-countryCode="GB" value="44">UK</option>
</select>

<input type="tel" placeholder ="956 826 4457" id="tel">