Хотя этот вопрос довольно старый и на него уже дан ответ, я подумал, что найду время, чтобы предложить пару вариантов, которые пока не рассматриваются в других ответах.
Учитывая исправленныеHTML (camelCasing с атрибутом id
):
<label year="2010" month="6" id="currentMonth"> June 2010</label>
Вы можете использовать регулярные выражения для извлечения названия месяца и года:
// gets the eleent with an id equal to 'currentMonth',
// retrieves its text-content,
// uses String.prototype.trim() to remove leading and trailing white-space:
var labelText = $('#currentMonth').text().trim(),
// finds the sequence of one, or more, letters (a-z, inclusive)
// at the start (^) of the string, and retrieves the first match from
// the array returned by the match() method:
month = labelText.match(/^[a-z]+/i)[0],
// finds the sequence of numbers (\d) of length 2-4 ({2,4}) characters,
// at the end ($) of the string:
year = labelText.match(/\d{2,4}$/)[0];
var labelText = $('#currentMonth').text().trim(),
month = labelText.match(/^[a-z]+/i)[0],
year = labelText.match(/\d{2,4}$/)[0];
console.log(month, year);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label year="2010" month="6" id="currentMonth"> June 2010</label>
Однако вместо регулярных выражений вы могли бы вместо этого использовать пользовательские атрибуты data-*
(которые работают в HTML 4.x, несмотря на то, что недопустимы для типа документа),но действительны в HTML 5):
var label = $('#currentMonth'),
month = label.data('month'),
year = label.data('year');
console.log(month, year);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
Обратите внимание, что при этом будет выведено 6
(для data-month
), а не 'June'
, как в предыдущем примере, хотя, если вы используетемассив для привязки чисел к названиям месяцев, которые можно легко решить:
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
label = $('#currentMonth'),
month = monthNames[+label.data('month') - 1],
year = label.data('year');
console.log(month, year);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
Аналогичным образом, вышеприведенное можно легко перенести на собственный DOM (в совместимых браузерах):
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
label = document.getElementById('currentMonth'),
month = monthNames[+label.dataset.month - 1],
year = label.dataset.year;
console.log(month, year);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label data-year="2010" data-month="6" id="currentMonth"> June 2010</label>
Ссылки: