【问题标题】:JQuery: Get jquery val on keypress from multiple ids with the same nameJQuery:从多个具有相同名称的 id 中获取按键上的 jquery val
【发布时间】:2016-06-14 03:59:59
【问题描述】:

希望任何人都可以提供帮助。 我有一个 php foreach 正在运行,我从数据库中获得了多个 acticles:

@foreach ($articles as $article)
   <div class="article">    
       <input id="comment" type="text"  class="materialize-textarea"  placeholder="Add comment"/>
   </div>
@endforeach

假设我在数据库中有 2 篇或更多篇文章。因此,在 html 方面,div 被重复,并且我有多个具有相同 id 的 div。

接下来我想让 jquery 获取输入值。这是示例代码

$("#comment").each(function()
{
            $(this).keypress(function(e) 
               {if (e.which == 13) 
                    alert('works');
                });
 });

结果:它在从数据库中提取的第一条记录上完美运行(第一篇文章)。在第二篇文章之后,JavaScript 根本不会触发。 我理解这个问题是因为 jQuery 只读取第一个 div。我在网上查看了一些解决方案,但没有什么对我真正有用。最合乎逻辑的解决方案似乎是将 .each 放入函数中。但结果是一样的。第一篇文章完美地触发了 JavaScript,其余的则没有。

注意:如果 php 代码看起来很奇怪,请忽略它,它是在 laravel 框架上的。尽管如此,它执行正确。 此处呈现的代码仅展示了应用程序的逻辑,并非实际代码。

【问题讨论】:

  • multiple divs with the same id ID 应该始终是唯一的 改用类

标签: javascript php jquery foreach keypress


【解决方案1】:

id 属性应该是唯一的,因为它用于唯一标识一个元素。 id 选择器只选择具有id 的第一个元素,因此使用class 代替元素组。

@foreach ($articles as $article)
   <div class="article">          
       <input class="comment" type="text"  class="materialize-textarea"  placeholder="Add comment"/>
       <!-------^---- set class instead of `id` ---------------------------------------------------> 
   </div>
@endforeach

那么就不需要使用 each() 对它们进行迭代,只需将 keypress() 事件处理程序直接绑定到选择器即可。

$(".comment").keypress(function(e){
//-^-------- class selector
   if (e.which == 13) 
      alert('works');
});

【讨论】:

  • 嗯。这比我想象的要容易。非常感谢@Pranav。你救了我
  • @Shavkat : 很高兴帮助你:)
  • 对不起另一个问题。所以为了更进一步,我将输入的值分配给一个变量。现在看起来像这样 $(".comment").keypress(function(e){ if (e.which == 13) var content = $(".comment").val(); });同样的事情正在发生。它只分配第一篇文章的价值。在其余部分中,值为空
  • @Shavkat : 你需要使用 $(this).val() ,`$(".comment").val();` 从该类的第一个元素中获取值
【解决方案2】:

HTML:

@foreach ($articles as $article)
   <div class="article">    
       <input id="comment" type="text"  class="materialize-textarea commentArea"  placeholder="Add comment"/>
   </div>
@endforeach

Javascript:

$(".commentArea").each(function(){
   $(this).keypress(function(e){
      if(e.which == 13){
         alert("OK");
      }
   });
});

我们不能使用相同的 ID。可以使用名称或类。使用类是最好的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2018-08-02
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多