【问题标题】:How to change button text belonging to a particular row in JS/jQuery?如何更改属于 JS/jQuery 中特定行的按钮文本?
【发布时间】:2019-06-12 18:49:50
【问题描述】:

我正在编写 html/php 代码,如下所示,在单击按钮时,我想将 Go 按钮文本更改为 Converting强>。

<?php  foreach ($programs as $key => $program) {  ?> 
   <tr data-index="<?php echo $key; ?>">
      <td><input style="text-align:center; width:90px;"  onclick="change()" type="submit"  id="go-btn" name="go-button" value="Go" data-id="<?php echo $key; ?>" ></input></td>
   </tr>
<?php }?>

此时,我在 UI 上有 2 行。以下是检查代码:

<tr data-index="0">
   <td><input onclick="change()" type="submit" id="go-btn" name="go-button" value="Go" data-id="0" class="go-btn btn btn-outline-primary">
   </td>
</tr>

<tr data-index="1">
   <td><input onclick="change()" type="submit" id="go-btn" name="go-button" value="Go" data-id="1" class="go-btn btn btn-outline-primary">
   </td>
</tr>

这是我尝试过的,但还有更多工作要做。

 function change() 
{
    var elem = document.getElementById("go-btn");
    var attribute = elem.getAttribute('data-id');
    console.log(attribute);  // It will print 0 everytime as it is taking the data-id value in the document. 
} 

问题陈述:

我想知道我应该在上面的 JS 代码 中进行哪些更改,以便在单击按钮时,按钮内的文本 属于特定行应从 Go 更改为 Converting

【问题讨论】:

  • 在同一个页面中,同一个 id 不应该有多个元素。 Id 应该在页面上具有唯一值。否则很多事情可能无法按预期工作。例如,getElementById 将始终只返回一个元素,无论页面中有多少具有相同 id 的元素
  • @Santi 这就是检查。可能我可以从 html/php 代码中删除 id。我正在将 foreach 循环与在检查时生成多行的表一起使用。
  • 如果你不使用那个 id 什么都不会发生,但是如果你打算使用它,你应该设计页面,以便每个 id 都有一个唯一的值。因为许多技术(css、javascript 等)假设每个 id 只属于一个元素并根据该假设工作

标签: javascript php jquery button getattribute


【解决方案1】:

您可以将单击事件侦听器添加到名称为 go-button 的输入中。如果您更改 .val,那么这将更改显示给用户的文本。在单击按钮后,我还禁用了按钮,因为我想这是您的预期行为(即用户必须等待转换完成)​​。

完成后,如有必要,您可以使用.attr("disabled", "false")重新启用该按钮

注意id 应该是唯一的,因此您应该尽可能尝试更改按钮的 ID。


演示

// Add click event to the inputs with class .go-button
$("input[name='go-button']").click( function() {

  // Change the text of the button, and disable
  $(this).val("Converting").attr("disabled", "true");
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr data-index="0">
   <td><input type="submit" id="go-btn" name="go-button" value="Go" data-id="0" class="go-btn btn btn-outline-primary">
   </td>
</tr>

<tr data-index="1">
   <td><input type="submit" id="go-btn" name="go-button" value="Go" data-id="1" class="go-btn btn btn-outline-primary">
   </td>
</tr>

【讨论】:

  • 它工作得很好。我有一个小问题。文本Converting 出现了一秒钟,然后转到Go
  • 很奇怪,听起来像其他东西正在设置输入的value?我会检查你的 JS 的其余部分
  • 我的错,你编辑了代码。后来我看到了编辑后的代码。我很抱歉。另外,我想知道当Converting 文本出现时如何更改按钮的宽度?转换文本似乎不适合按钮。
  • 我已经编辑了问题以显示之前的内容。
  • 可以说,当转换文本出现时,我希望宽度为 120px
猜你喜欢
  • 2013-04-15
  • 2011-07-31
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 2016-01-04
  • 2011-04-29
相关资源
最近更新 更多