尝试使用jQuery更改语言

Trying to Change Language with jQuery

本文关键字:语言 jQuery      更新时间:2023-09-26

我正在学习本教程,它概述了一种使用jQuery使网站成为多语言网站的简单方法。首先,我非常精通HTML/CSS和PHP/MySQL,但我才刚刚开始使用JavaScript。

我花了一些时间在网上搜索,但我找不到我的代码有问题。这是我的东西。

我的HTML代码如下:

<h5 class="info-text">Be notified when we launch.</h5>

根据教程,我的XML如下所示:

<?xml version="1.0" encoding="UTF-8"?>
    <translations>
   <translation id="info-text">
    <english>Be notified when we launch</english>
    <spanish>notificar cuando tu lanza</spanish>
   </translation>
    </translations>

(对不起,我的西班牙语不是很好。但这只是为了测试目的)。

我的jQuery脚本如下:

<script type="text/javascript" language="javascript">
$(function() {
    var language = 'english';
    $.ajax({
        url: 'includes/languages.xml',
        success: function(xml) {
            $(xml).find('translation').each(function(){
                var id = $(this).attr('id');
                var text = $(this).find(language).text();
                $("." + id).html(text);
            });
        }
    });
});
</script>

我确实在标题中包含了jQuery文件,如下所示:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.3.min.js"></script>

不确定我做错了什么。任何帮助都将不胜感激。谢谢

您的选择器错误$("." + id).html(text);更改为$("#" + id).html(text);

我写那篇文章的时候一定很累。很明显,你的目标是一个类,而不是ID。很抱歉浪费时间。

现在来解决手头的问题。

让我们假设您的标记是(源自您的)

<h5 class="info-text">put stuff here.</h5>
<h5 class="charlie">charlie.</h5>
<h5 id="walt">walt.</h5>

我们的XML是(也以您的形式,但有更多):

  <?xml version="1.0" encoding="UTF-8"?>
  <translations>
    <translation id="info-text">
      <english>Be notified when we launch</english>
      <spanish>notificar cuando tu lanza</spanish>
    </translation>
    <translation id="walt">
      <english>Be notified when we launch for walt</english>
      <spanish>notificar cuando tu lanza for walt</spanish>
    </translation>
    <translation id="charlie">
      <english>Be notified when we launch for charlie</english>
      <spanish>notificar cuando tu lanza for charlie</spanish>
    </translation>
  </translations>

然后,我们必须解决XML的问题,并通过ajax检索它

为了声明手头的任务,我们希望基于一种语言来替换页面上元素的文本(请参阅上面的标记),这些元素通过指向页面元素的属性与传入XML(来自ajax)指向的元素相匹配。

这样一来,您的代码看起来非常接近,但ajax中的XML可能有问题。它必须是XML,而不是类型中的文本(字符串),以便像您所做的那样使用jQuery来选择它。很简单,让我们不要告诉我们的ajax作为XML进行pull。jQuery的早期版本将XML作为ajax的默认值,但我们不要相信这一点,并通过添加:dataType: "xml", 来强制它为XML

$(function() {
    var language = 'english';
    $.ajax({
        url: 'includes/languages.xml',
        dataType: "xml"
    }).done(function(xml) {
        $(xml).find('translation').each(function(){
            var id = $(this).attr('id');
            var text = $(this).find(language).text();
            $("." + id).html(text);
        });
    });
});

现在应该可以具体解决您的问题了


自定义只是因为我很感兴趣,但这是一个有用的练习

这对你的使用来说可能有些过头了,但仍然很有趣

注意:假设"xmlDoc"包含来自ajax或其他内容的xml文档。

然而,只要稍微做一组更改,我们就可以针对不同类型的元素(按类、id等)。

HTML用于自定义:

<div id="container">
  <h5 id="info-text">put stuff here.</h5>
  <h5 class="charlie">charlie.</h5>
  <h5 mycustom="bill">bill.</h5>
  <h5 class="bill">bill.</h5>
  <h5 id="walt">walt.</h5>
  <h5 id="walter">walter custom.</h5>
</div>

自定义xml:

<?xml version="1.0" encoding="UTF-8"?>
<translations>
  <translation id="info-text">
    <english>Be notified when we launch</english>
    <spanish>notificar cuando tu lanza</spanish>
  </translation>
  <translation id="walt" custom="[id=walter]">
    <english>Be notified when we launch for walt</english>
    <spanish>notificar cuando tu lanza for walt</spanish>
  </translation>
  <translation id="charlieidthing" class="charlie">
    <english>Be notified when we launch for charlie</english>
    <spanish>notificar cuando tu lanza for charlie</spanish>
  </translation>
  <translation customAttribute="mycustom,bill" targetclass="bill">
    <english>Be notified when we launch for bill</english>
    <spanish>notificar cuando tu lanza for bill</spanish>
  </translation>
</translations>

这是自定义代码来处理所有这些:

var language = "spanish";
function decodeSelector(encoded) {
  var elem = document.createElement('textarea');
  elem.innerHTML = encoded;
  var decoded = elem.value;
  return decoded;
}
function getSelector(attr) {
  var xType = attr.localName;
  var xSelect = attr.nodeValue;
  // here we match the custom attributes in the markup/enhance as needed
  switch (xType) {
    // class either in class or targetclass attributes
    case "class":
    case "targetclass":
      xSelect = "." + xSelect;
      break;
    // id in id or targetid attributes
    case "id":
    case "targetid":
      xSelect = "#" + xSelect;
      break;
    // some custom attribute with a name,value content pair
    // example in XML: customAttribute="mycustom,bill"
    case "customAttribute":
      var s = xSelect.split(",");
      xSelect = "[" + s[0] + "='" + decodeSelector(s[1]) + "']";
      break;
    // some encoded selector (any jQuery selector)
    case "custom":
      xSelect = decodeSelector(xSelect);
      break;
    // used to ignore other attributes
    default:
      xSelect = "";
      break;
  }
  return xSelect;
}
function setTarget(targetPick, languageText) {
  var attrs = targetPick.attributes;
  for (var j = 0; j < attrs.length; j++) {
    var xSelect = getSelector(attrs[j]);
    if (xSelect) {
      var target = $(xSelect);
      //  target.css('background-color', 'pink'); you can do this also
      target.text(languageText);
    }
  }
}

现在处理它(这已经在文档中准备好了,但应该在ajax中完成):

$(function() {
  $(xmlDoc).find('translation').each(function() {
    var targetTranslation = $(this).find(language);
    var text = targetTranslation.text();
    setTarget(this, text);
  });
});

这里有一个自定义的小提琴(注意,我使用了一个XML字符串并对其进行了解析)https://jsfiddle.net/MarkSchultheiss/z8qbsku4/