【问题标题】:Using a variable and an id inside a querySelector在 querySelector 中使用变量和 id
【发布时间】:2017-02-22 16:27:21
【问题描述】:

我想使用 querySelector 从输入列中获取值。我需要使用两个 id 来获取正确的列。第二个 id 存储在一个变量中,它是一个整数值。我尝试了不同的东西,但我什么也没得到。目前它给了我null。

 checkDescriptionField = document.querySelector('#methodProperties input#'+'descriptionFieldId'); 
 if(typeof checkDescriptionField !== 'undefined' && checkDescriptionField !== null)
        {
            descriptionFieldValue = document.querySelector('#methodProperties input#'+'descriptionFieldId').textContent; 
        }

外部 id 是 methodProperties,内部是 input id="0eca409e-e2f7-467d-bd5e-dff9b63e3715" 我想得到它的值 ="Customers"

<div id="methodProperties">
<td role="gridcell">
<input id="0eca409e-e2f7-467d-bd5e-dff9b63e3715" class="k-textbox gridTable propertiesField" value="Customers" readonly="" data-role="droptarget"   type="text">
<span class="errorTooltip" style="display: none;">
<span class="deleteTooltip" style="padding: 5px; display: inline;" title="Delete Value" data-role="tooltip">
</td>

我试过了,但我得到了无效的错误

checkDescriptionField = document.querySelector('#methodProperties input#'+descriptionFieldId); 
if(typeof checkDescriptionField !== 'undefined' && checkDescriptionField !== null)
        {
            descriptionFieldValue = document.querySelector('#methodProperties input#'+descriptionFieldId).textContent; 
        }

【问题讨论】:

  • 查看@gurvinder372 的回答。顺便说一句,这与 jQuery 无关。
  • 有相同id的重复列
  • @Masood 大错特错因为 ID 在文档上下文中必须是唯一的
  • 没关系,还是和jQuery无关。糟糕的 html 结构...只使用一次 id。
  • 顺便说一句,你有一个td 作为div 的直接子代,仍然无效!!!看在上帝的份上,谁写了这个 HTML 标记?!.... 如果是同事,请告诉你的老板在他烧毁办公室之前解雇他

标签: javascript jquery-selectors


【解决方案1】:

外层id是methodProperties,内层是input id="0eca409e-e2f7-467d-bd5e-dff9b63e3715" 我想得到它的价值 ="客户"

试试这个

descriptionFieldValue = document.querySelector( '#' + descriptionFieldId ).value; 

或者因为methodProperties中只有一个输入

descriptionFieldValue = document.querySelector( '#methodProperties input' ).value; 

如果要重复 id,则使用 data-id 属性代替

<div data-id="methodProperties">
  <td role="gridcell">
    <input value="customers">
  </td>
</div>

和js一样

descriptionFieldValue = document.querySelector( 'div[data-id="methodProperties"] input' ).value;  //this will take the value from first methodProperties

【讨论】:

  • 有相同 id 的重复 colmn 但外部 div 不同,所以我需要使用外部 div
  • 输入栏不止1个 我刚刚贴了一段代码
  • @Masood 您可以为所需的输入分配一个类并在选择器中使用它。
【解决方案2】:

您应该使用document.querySelector(...).value 而不是.textContent。这样您就可以访问输入字段的值。

https://jsfiddle.net/e0h0ajdb/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多