如果输入字段在数组中找到值,请执行此操作(jQuery/Javascript)

if input field has a value found in array, do this (jQuery/Javascript)

本文关键字:操作 执行 jQuery Javascript 字段 输入 数组 如果      更新时间:2023-09-26

我有一个页面,里面有几个输入字段。

我需要找到具有值数组的字段,如果是,.remove() closest('tr')

标记与此类似

<table>
  <tr>
    <td>
      <input type="text" value="this">
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" value="that">
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" value="them">
    </td>
  </tr>
</table>

我需要找到"这个"和"那个",如果它们在那里,请删除它们的<tr>容器(和他们自己),这样我最终会得到:

<table>
  <tr>
    <td>
      <input type="text" value="them">
    </td>
  </tr>
</table>

我试过这个:

jQuery(document).ready(function($){
    var badfields = ['this', 'that'];
    var fieldvalue = $('input[type="text"]').val();
    if($.inArray(fieldvalue, badfields) > -1){
        $(this).closest('tr').remove();   
    }
});

但它似乎不想工作?

您需要使用 .each 遍历所有字段,因此如下所示:

$('input[type="text"]').each(function() {
    var fieldvalue = $(this).val();
    if ($.inArray(fieldvalue, badfields) > -1) {
        $(this).closest('tr').remove();   
    }
});

示例:jsfiddle

有时使用 jQuery

可以非常简洁。 jQuery有内容选择器,你可以用于这种类型的目的:

$("input[type=text][value=this], [value=that]").parents("tr").remove();

由于您不一定事先知道thisthat,因此您可以执行以下操作:

var badfields = ['this', 'that'];
$(badfields).each(function(i) { 
    $("input[type=text][value=" + this + "]").parents("tr").remove();
});

您可以使用每个来循环访问选择器。 inArray范围内的this不是您要查找的元素。

演示:http://jsfiddle.net/

.html:

<table>
 <tr>
  <td>
  <input type="text" value="this">
  </td>
 </tr>
 <tr>
  <td>
   <input type="text" value="that">
  </td>
 </tr>
 <tr>
  <td>
   <input type="text" value="them">
  </td>
 </tr>
</table>

.js:

jQuery(document).ready(function($){
 var badfields = ['this', 'that'];
    $('input[type="text"]').each(function(){
        if( $.inArray(this.value, badfields) > -1 ){
            $(this).closest('tr').remove();
        }
    });
});