Javascript/Jquery 获取子元素,减去字符串并替换

Javascript/Jquery get child element, substract string and substitute

本文关键字:字符 字符串 串并 替换 Jquery 获取 元素 Javascript      更新时间:2023-09-26

我看了很多,但我找不到解决问题的方法:c 我不是 JS 专家,但这对程序员来说可能很容易。

我有一个列表,一个导航列表:

<ul id="menu-navbar">
   <li id="menu-item-270-en" class="lang-item">
     <a href="site.com/en">
       English
     </a>
   </li>
   <li id="menu-item-270-pt" class="lang-item">
     <a href="site.com/">
       Português
     </a>
   </li>
</ul>

两件事:我需要从<li>内部的<a>中获取文本(英语),减去并仅返回前 2 个字母。我希望网站显示 En。对于葡萄牙语的文本,我希望它显示Pt。替换();功能应该可以,不是吗?

不能在<a>中插入id和类,因为它是由Wordpress中的插件生成的。

对于完整代码,网站 http://yogmel.com,右上角的列表位于导航栏上。

注意:英文网站尚未完全正常运行。

非常感谢!

对于您的要求,最好维护一个映射对象。

jQuery

var langListMap = [{
  text: "English",
  shortName: "En"
}, {
  text: "Português",
  shortName: "Pt"
}]
$(document).ready(function(){
  $.each($("a"), function(i,a){
    var sName = getObject($(a).text());
    if(sName){
      $(a).text(sName.shortName);
    }
  });
})
function getObject(text){
  console.log(text)
  return langListMap.filter(function(a){
    return a.text === text.trim();
  })[0]
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<ul id="menu-navbar">
  <li id="menu-item-270-en" class="lang-item">
    <a href="site.com/en">
       English
     </a>
  </li>
  <li id="menu-item-270-pt" class="lang-item">
    <a href="site.com/">
       Português
     </a>
  </li>
  <li id="menu-item-270-pt" class="lang-item">
    <a href="site.com/">
       Test
     </a>
  </li>
</ul>

纯 JS

var langListMap = [{
  text: "English",
  shortName: "En"
}, {
  text: "Português",
  shortName: "Pt"
}]
function getObject(text) {
  return langListMap.filter(function(a) {
    return a.text === text.trim();
  })[0]
}
(function() {
  var a = document.getElementsByTagName("a");
  for (var i = 0; i < a.length; i++) {
    var sName = getObject(a[i].innerHTML);
    if (sName) {
      a[i].innerHTML = sName.shortName;
    }
  }
})();
<ul id="menu-navbar">
  <li id="menu-item-270-en" class="lang-item">
    <a href="site.com/en">
       English
     </a>
  </li>
  <li id="menu-item-270-pt" class="lang-item">
    <a href="site.com/">
       Português
     </a>
  </li>
  <li id="menu-item-270-pt" class="lang-item">
    <a href="site.com/">
       Test
     </a>
  </li>
</ul>

为此使用普通的JavaScript,而不是使用jQuery库,我建议:

'use strict'
// declaring the variable 'abbreviationsMap' as a 'constant'
// to prevent rebinding later in the script (although it can
// still be updated, eg:
// abbreviationsMap.English = 'xy', or
// abbreviationsMap.Welsh = 'cy'
const abbreviationsMap = {
  'English': 'En',
  'Português': 'Pt'
};

// named function to handle the creation of abbreviations,
// with user-supplied options:
function abbreviations(opts) {
  // declaring variables using 'let' to limit the
  // variables to the scope of the block in which
  // they're declared:
  let settings = {
    // the CSS selector by which the elements whose
    // content should be abbreviated should be selected:
    'selector': '.toAbbreviate',
    // the map of full-words-to-abbreviations to use:
    'abbreviations': abbreviationsMap
  };
  // iterating over the properties declared in the
  // opts Object to update the settings:
  for (let property in opts) {
    // if the opts Object has a named property
    // not inherited from its prototype equal to
    // the current property-name:
    if (opts.hasOwnProperty(property)) {
      // we update the same property of the
      // settings Object to match the value
      // from the opts Object:
      settings[ property ] = opts[ property ];
    }
  }
  // finding the elements from the document that match the
  // CSS selector:
  let elements = document.querySelectorAll( settings.selector );
  // converting that NodeList to an Array, using Array.from():
  let elementsArray = Array.from( elements );
  // iterating over the Array:
  elementsArray.forEach(function(abbr) {
    // 'abbr' the first-named argument of the anonymous function
    // is automatically supplied by the function itself, and is
    // a reference to the array-element of the array over which
    // we're iterating.
    // setting the title property of the array-element to
    // offer an explanation of what the abbreviation means,
    // removing any leading/trailing white-space using
    // String.prototype.trim():
    abbr.title = abbr.textContent.trim();
    // updating the textContent of the element to match the
    // abbreviation held in the settings.abbreviation Array,
    // or, if that's a falsy value, simply returns the title
    // of the element:
    abbr.textContent = settings.abbreviations[abbr.title] || abbr.title;
  });
}
// calling the function, and modifying the CSS selector
// to be used within the function:
abbreviations({
  'selector': '.lang-item a'
});

'use strict'
const abbreviationsMap = {
  'English': 'En',
  'Português': 'Pt'
};
function abbreviations(opts) {
  let settings = {
    'selector': '.toAbbreviate',
    'abbreviations': abbreviationsMap
  };
  for (let property in opts) {
    if (opts.hasOwnProperty( property )) {
      settings[property] = opts[ property ];
    }
  }
  let elements = document.querySelectorAll( settings.selector );
  let elementsArray = Array.from( elements );
  elementsArray.forEach(function( abbr ) {
    abbr.title = abbr.textContent.trim();
    abbr.textContent = settings.abbreviations[ abbr.title ] || abbr.title;
  });
}
abbreviations({
  'selector': '.lang-item a'
});
<ul id="menu-navbar">
  <li id="menu-item-270-en" class="lang-item">
    <a href="site.com/en">
       English
     </a>
  </li>
  <li id="menu-item-270-pt" class="lang-item">
    <a href="site.com/">
       Português
     </a>
  </li>
  <li id="menu-item-270-cy" class="lang-item">
    <a href="site.com/cy">
       Welsh
     </a>
  </li>
</ul>

JS小提琴演示。

或者,另一种方法是:

'use strict'
// again, a named function to convert the textContent
// of relevant items into an abbreviated form:
function abbreviations(opts) {
  let settings = {
    // the CSS selector with which the elements should
    // be selected
    'selector': '.toAbbreviate',
    // the property of the element, or its ancestor element,
    // from which the abbreviation should be derived:
    'property': 'id',
    // the regular expression by which the abbreviation
    // should be derived,
    // this is looking for a sequence of lower-case 
    // alphabetical characters in the range from 'a' to 'z'
    // ('[a-z]') inclusive, that's two characters in length
    // ('{2}') and occurs at the end of the property-string
    // ('$'):
    'regexp': /[a-z]{2}$/
  };
  for (let property in opts) {
    if (opts.hasOwnProperty(property)) {
      settings[property] = opts[property];
    }
  }
  let elements = document.querySelectorAll(settings.selector);
  let elementsArray = Array.from(elements),
    text;
  elementsArray.forEach(function(abbr) {
    // finding the closest ancestor element to the current
    // element that has the property identified in the
    // settings.property value, using CSS attribute-selector
    // syntax (identifying an 'id' property/attribute by '[id]'
    // for example;
    // accesing the property identified by the settings.property
    // value of the found element, retrieving the 'id' by:
    // HTMLElement[ id ], 
    // and retrieving the portion of the property-value
    // that matches the settings.regexp property-value,
    // (or null if there is no match):
    text = abbr.closest('[' + settings.property + ']')[settings.property].match(settings.regexp);
    // because null is a possible result, we check
    // that the text variable exists:
    if (text) {
      // if it does, then we retrieve the match
      // held at the first index of the returned
      // Array:
      text = text[0];
    } else {
      // otherwise we simply use the trimmed text-content:
      text = abbr.textContent.trim();
    }
    // setting the title of the element:
    abbr.title = abbr.textContent.trim();
    // capitalising the first character of the String and
    // concatenating that with the rest of the String:
    abbr.textContent = text.charAt(0).toUpperCase() + text.slice(1);
  });
}
abbreviations({
  'selector': '.lang-item a'
});

'use strict'
function abbreviations(opts) {
  let settings = {
    'selector': '.toAbbreviate',
    'property': 'id',
    'regexp': /[a-z]{2}$/
  };
  for (let property in opts) {
    if (opts.hasOwnProperty(property)) {
      settings[property] = opts[property];
    }
  }
  let elements = document.querySelectorAll(settings.selector);
  let elementsArray = Array.from(elements),
    text;
  elementsArray.forEach(function(abbr) {
    text = abbr.closest('[' + settings.property + ']')[settings.property].match(settings.regexp);
    if (text) {
      text = text[0];
    } else {
      text = abbr.textContent.trim();
    }
    abbr.title = abbr.textContent.trim();
    abbr.textContent = text.charAt(0).toUpperCase() + text.slice(1);
  });
}
abbreviations({
  'selector': '.lang-item a'
});
<ul id="menu-navbar">
  <li id="menu-item-270-en" class="lang-item">
    <a href="site.com/en">
       English
     </a>
  </li>
  <li id="menu-item-270-pt" class="lang-item">
    <a href="site.com/">
       Português
     </a>
  </li>
  <li id="menu-item-270-cy" class="lang-item">
    <a href="site.com/cy">
       Welsh
     </a>
  </li>
</ul>

JS小提琴演示。