我试图将 p 标记中的文本抓取到变量中。 p 标签称为#musCardImageTitle,是该页面上背景图像的描述。但是,它不起作用。我不知道为什么
var desc = document.getElementById("musCardImageTitle").innerHTML;
document.getElementById("sb_form_q").placeholder = desc
//the second line is putting that text into a searchbox as placeholder text
如果有帮助的话,这是 Bing 主页的内容。如果有帮助的话,我已经添加了一张我正在尝试做的事情的图片
我认为这应该很容易,但由于某种原因我无法让它工作......
最佳答案
试试这个
// select the target node
var target = document.querySelector('#musCardImageTitle');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//document.getElementById("sb_form_q").value = mutation.target.textContent ;
document.getElementById("sb_form_q").placeholder = mutation.target.textContent;
observer.disconnect();
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
此示例位于 MutationObserver doc
关于javascript - 将innerHTML 抓取到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27149200/