Add a digit to the end of multiple attributes

javascript jquery

45 观看

2回复

134 作者的声誉

I'm trying to grab the end digit of the target div, replace and join two attributes (js-data-reveals) with that digit added at the end (_1).

I know it has something to do with the regular expression that I am using to replace the attributes but I can't figure it out.

Hope you can help.

$('#js-form-group-UPLOAD_DOCUMENT_ID_1').find('input').each(function() {
  var attrName = 'js-data-reveals';
  var $el = $(this);
  //Get Last Digit from ID
  var idNumber = $el.attr('id').match(/\d+$/);
  var attrs = $el.attr(attrName);
  //Split the two attributes in js-data-reveals
  var data = attrs.split(',').map(function(item) {
    return item.replace(/.{0}$/, function(idNumber) {
      return idNumber
    });
  });
  $el.attr(attrName, data.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="js-form-group-UPLOAD_DOCUMENT_ID_1">
  <fieldset>
    <input type="file" class="form-control" id="UPLOAD_DOCUMENT_ID_1"
           js-data-driven="true"
           js-data-reveals="DOCUMENT_TYPE,UPLOAD_DOCUMENT_DESCRIPTION">
  </fieldset>
</div>

作者: Qbessi 的来源 发布者: 2017 年 12 月 27 日

回应 2


0

351 作者的声誉

Remove the '+' in your Regular Expression to make it:

var idNumber = $el.attr('id').match(/\d$/);

The '+' makes a Regular Expression match the given character 1 or more times, so \d+$ would match 12345 in 'd12345'. Since you only want the last digit to match, removing the '+' will make it works as expected.

作者: Murad Khan 发布者: 2017 年 12 月 27 日

1

148171 作者的声誉

决定

match() returns an array.

Can simplify this using attr(attrName, function)

$('input[js-data-reveals]').attr('js-data-reveals', function(_, existing) {
  var idNumber = this.id.match(/\d+$/)[0];
  return existing.split(',').map(function(s) {
    // replace number if it already exists or add it if it doesn't
    return s.match(/_\d+$/) 
           ? s.replace(/\d+$/, idNumber)
           : s += '_' + idNumber;
  }).join();
});


console.log($('#UPLOAD_DOCUMENT_ID_1').attr('js-data-reveals'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="js-form-group-UPLOAD_DOCUMENT_ID_1">
  <fieldset>
    <input type="file" 
       class="form-control" 
       id="UPLOAD_DOCUMENT_ID_1" 
       js-data-driven="true" 
       js-data-reveals="DOCUMENT_TYPE,UPLOAD_DOCUMENT_DESCRIPTION_999">
  </fieldset>

</div>

作者: charlietfl 发布者: 2017 年 12 月 27 日
32x32