选择具有使用子字符串创建的变量的元素

Selecting element with variable that has been made using substring

我有一个数组,我想删除最后一个为“0”的符号。这就是为什么我使用 substring 来删除它并且我试图将此变量用作 jQuery selector 的原因。但是当我使用子字符串时它不会 select 元素。

我的代码是:

  
var key = 'director_front_passport0';
   
var document_name = key.substring(0,key.length - 1);
console.log(document_name); //returns director_front_passport

$('#' + document_name).append('<label class="error file_error">test</label>');
//I want to select element with id=director_front_passport

      
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="director_front_passport" id="director_front_passport" />

如果我已经使用 substring,我应该如何 select 具有明确 id 的元素?

如果您附加到 div,您的代码就可以工作。您不能附加到输入字段

试试 after :

var response = {
  errors: {
    'director_front_passport0': "error1",
    'director_back_passport0': "error2",
    'director_address_document0': "error3"
  }
}

$.each(response.errors, function(key, value) {

  var files_array = ['director_front_passport0', 
                     'director_back_passport0', 
                     'director_address_document0'];
  if ($.inArray(key, files_array) !== -1) {

    var document_name = key.substring(0, key.length - 1);
    console.log(document_name); //returns for example director_front_passport

    $('#' + document_name).after('<label class="error file_error">test</label>');
    //I want to select element with id=director_front_passport

  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="file" id="director_front_passport" /><hr/>
<input type="file" id="director_back_passport" /><hr/>
<input type="file" id="director_address_document" />