简体   繁体   English

如何分配 button.setAttribute('name', 'value') javascript 变量的值

[英]How do I assign value of button.setAttribute('name', 'value') a javascript variable

First, here is the javascript code.首先,这是 javascript 代码。

    const nameId = calledVariable.value // This variable is an input from a form

    // Create the button
    var payButton = document.createElement('input');
    payButton.setAttribute('type', 'button');
    payButton.setAttribute('value', 'UNPAID');
    payButton.setAttribute('class', 'unpaidButton');
    payButton.setAttribute('id', nameId); // This needs to be text of input
    payButton.setAttribute('onClick', 'updateButton(this.id)');

and this is the HTML result这是 HTML 结果

<input type="button" value="UNPAID" class="unpaidButton" id="" onclick="updateButton(this.id)">

How do I get the HTML/javascript to recognize nameId as it's value?如何让 HTML/javascript 将nameId识别为它的值?

You don't need to use ${...} to pass the var value to the setAttribute function. Use only the variable name.您不需要使用 ${...} 将 var 值传递给 setAttribute function。仅使用变量名称。 Like that:像那样:

 const nameId = 123; const payButton = document.querySelector('button'); console.log('before', payButton) payButton.setAttribute('id', nameId); const check = document.querySelector('button'); console.log('after',check)
 <button>button</button>

And I solved my own question... use the following in the code...我解决了我自己的问题......在代码中使用以下......

payButton.setAttribute('id', `${nameId}`);

This is a Facepalm moment...这是一个Facepalm时刻......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM