Привет, поэтому я создал этот код, который отлично работает.Как заменить анонимную функцию именованной функцией в javascript?
document.getElementById("file").addEventListener('click',
function() {
var textArea = document.getElementById("newTextArea");
//Retrieve the selected text :
var selText = window.getSelection();
var text = textArea.innerHTML;
// I need to make a condition here. If the text doesn't have a span tag then do this:
if (document.querySelector('.test') === null) {
textArea.innerHTML = text.replace(selText, '<span class="test">'+selText+'</span>');
// if the text does have a span tag then remove the span tag
} else if (document.querySelector('.test') !== null) {
var deSelText = document.querySelector('.test');
var highlightedText = deSelText.innerHTML;
var parent = deSelText.parentNode;
var newNode = document.createTextNode(highlightedText);
parent.insertBefore(newNode, deSelText);
parent.removeChild(deSelText);
}
}, false);
Но я хотел бы сделать анонимную функцию в имени функции, так это выглядит следующим образом:
document.getElementById("file").addEventListener('click', classAndSpan(test), false);
здесь названная функция:
function classAndSpan(addClass) {
var textArea = document.getElementById("newTextArea");
//Retrieve the selected text :
var selText = window.getSelection();
var text = textArea.innerHTML;
// I need to make a condition here. If the text doesn't have a span tag then do this:
if (document.querySelector('.' + addClass) === null) {
textArea.innerHTML = text.replace(selText, '<span class="' + addClass + '">'+selText+'</span>');
// if the text does have a span tag then remove the span tag
} else if (document.querySelector('.' + addClass) !== null) {
var deSelText = document.querySelector('.' + addClass);
var highlightedText = deSelText.innerHTML;
var parent = deSelText.parentNode;
var newNode = document.createTextNode(highlightedText);
parent.insertBefore(newNode, deSelText);
parent.removeChild(deSelText);
}
}
я пропускаю что-то потому, что эта именованная функция не работает. Я возвращаю что-то в функции, и если да, то что мне вернуть?
Спасибо за помощь, очень ценю.
Возможный дубликат [Как передать параметр в функцию, используя в addEventListener?] (Http://stackoverflow.com/questions/12024483/how-to-pass-parameter-to-function-using-in-addeventlistener) – Xufox