【问题标题】:Grabbing innerHTML into a variable将innerHTML抓取到一个变量中
【发布时间】:2014-11-26 12:25:50
【问题描述】:

我正在尝试将 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 主页。如果有帮助,我已经包含了我正在尝试做的事情的图片

http://i.stack.imgur.com/bJeU8.jpg

我认为这应该很容易,但由于某种原因我无法让它工作......

【问题讨论】:

标签: javascript html firefox greasemonkey userscripts


【解决方案1】:

试试这个

// 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

【讨论】:

  • 那个成功了!但最终它变成了真正的文本而不是占位符。但我还是很感激,谢谢。认为这会比这更容易,这似乎是不必要的复杂。谢谢你
  • 能够将 .value 更改为 .placeholder ,这正是我想要的。感谢您的帮助
【解决方案2】:

试试这个

var desc = document.getElementById("musCardImageTitle").value;

【讨论】:

  • 没什么。它给出了“未定义”。
猜你喜欢
  • 2019-03-28
  • 2019-11-11
  • 2013-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 2013-01-10
相关资源
最近更新 更多