在 DOM 中通过 id 获取元素
Getting element by id in DOM
我正在创建一个 element,然后想给它添加一个事件侦听器。我在做:
console.log('about to create modal');
this.createModal(
'There are unsubmitted changes in this Access Request.',
'Do you wish to discard them?',
'Yes',
'No',
'tabCloseModal'
);
console.log('created modal');
const modal = this.shadowRoot.querySelector('#tabCloseModal');
console.log(`modal = ${modal}`);
modal.addEventListener('px-modal-accepted', function(e) {
console.log('removing tab');
this.removeTab(index);
});
其中 createModal
创建一个元素:
createModal(headerText, bodyText, acceptText, rejectText, id, opened = true) {
const modal = document.createElement('px-modal');
//assign parameters
document.swQuerySelector('body').appendChild(modal);
console.log('Child appended');
modal.visible = true;
this.fire('modal-visible');
}
无论我做什么(我累了swQuerySelector
、swQuerySelectorAll
、querySelector
、querySelectorAll
),我似乎无法掌握模态.当我记录它时,它只是显示为空的、未定义的或 [object Object] 或类似的东西,我从来没有达到 'removing tab'。我错过了什么?模态出现了,但是接受的事件侦听器的映射不起作用。
解决这个问题:
Return 来自 createModal
的模式,并确认它在调用代码中按预期工作。
如果是,则问题出在您的 this.shadowRoot.querySelector
行。在那个点设置一个断点,并在开发工具 command line
中尝试一些通往 querySelector
的路径,直到你得到你的模态。尝试在你的 devtools elements
window 中找到模式,看看它在哪里。在没有看到您的 DOM 布局的情况下,我们无法建议父元素的确切路径。
暗影DOM有时可以'shady'...
我正在创建一个 element,然后想给它添加一个事件侦听器。我在做:
console.log('about to create modal');
this.createModal(
'There are unsubmitted changes in this Access Request.',
'Do you wish to discard them?',
'Yes',
'No',
'tabCloseModal'
);
console.log('created modal');
const modal = this.shadowRoot.querySelector('#tabCloseModal');
console.log(`modal = ${modal}`);
modal.addEventListener('px-modal-accepted', function(e) {
console.log('removing tab');
this.removeTab(index);
});
其中 createModal
创建一个元素:
createModal(headerText, bodyText, acceptText, rejectText, id, opened = true) {
const modal = document.createElement('px-modal');
//assign parameters
document.swQuerySelector('body').appendChild(modal);
console.log('Child appended');
modal.visible = true;
this.fire('modal-visible');
}
无论我做什么(我累了swQuerySelector
、swQuerySelectorAll
、querySelector
、querySelectorAll
),我似乎无法掌握模态.当我记录它时,它只是显示为空的、未定义的或 [object Object] 或类似的东西,我从来没有达到 'removing tab'。我错过了什么?模态出现了,但是接受的事件侦听器的映射不起作用。
解决这个问题:
Return 来自
createModal
的模式,并确认它在调用代码中按预期工作。如果是,则问题出在您的
this.shadowRoot.querySelector
行。在那个点设置一个断点,并在开发工具command line
中尝试一些通往querySelector
的路径,直到你得到你的模态。尝试在你的 devtoolselements
window 中找到模式,看看它在哪里。在没有看到您的 DOM 布局的情况下,我们无法建议父元素的确切路径。
暗影DOM有时可以'shady'...