이벤트 처리와 함께 "외부"변수를 변경하는 방법이 있는지 알고 싶습니다.
function generateHTML()
{
var html = '';
// Some html generating code
html += '<b>John Doe</b>';
$(document).trigger('html:generating', html);
// Do more hardcoded stuff with html
$(document).trigger('html:generated', html);
return html;
}
$(document).on('html:generating', function(e, html) {
html = '<span>' + html + '</span>';
});
$(document).on('html:generated', function(e, html) {
console.log(html); // prints <b>John Doe</b>
// expected <span><b>John Doe</b></span>
});
generateHTML();
이것은 Mustache (또는 다른 템플릿 라이브러리) 동적 html 코드를 처리 할 때 매우 유용합니다.
참조로 html을 전달하는 것에 대해 이야기하는 경우이를 수행하는 방법이 있습니다. 함수 인수로 전달하는 모든 것은 값으로 전달되지만 객체를 전달하는 경우 포인터가 복사되므로 객체 속성은 여전히 원래 값을 가리 킵니다. 따라서 다음과 같이 할 수 있습니다.
function generateHTML()
{
var container={html: ''};
// Some html generating code
container.html += '<b>John Doe</b>';
$(document).trigger('html:generating', container);
// Do more hardcoded stuff with html
$(document).trigger('html:generated', container);
return container.html;
}
$(document).on('html:generating', function(e, container) {
container.html = '<span>' + container.html + '</span>';
});
$(document).on('html:generated', function(e, container) {
console.log(container.html);
});
generateHTML();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다