Javascript jQuery在控制台中工作,但不在.js文件中工作
在Javascript jQuery在控制台中工作,但不在.js文件中工作,javascript,jquery,html,tampermonkey,Javascript,Jquery,Html,Tampermonkey,在googlechromesnippet中工作,但未加载Tampermonkey 我认为它试图在找到目标之前设定一个值 (编辑) 全文: $('ul#test a').click(function(){ $('this').closest('parent').find('textarea').val(this.getAttribute('href')); }); /==UserScript== //@name新用户脚本 //@名称空间http://tampermonkey.net/ /
googlechrome
snippet中工作,但未加载Tampermonkey
我认为它试图在找到目标之前设定一个值 (编辑) 全文:
$('ul#test a').click(function(){
$('this').closest('parent').find('textarea').val(this.getAttribute('href'));
});
/==UserScript==
//@name新用户脚本
//@名称空间http://tampermonkey.net/
//@version 0.1
//@description尝试接管世界!
//@author You
//@match www.reddit.com/r/some-subreddit
//@grant none
//==/UserScript==
(功能(){
"严格使用",;
$(“textarea”).one(“单击”,(函数(){
$(“.usertext edit”).prepend(`
将您的代码放入
ready
函数中,这样事件将在选择器中找到元素,因为它将在DOM满载后执行:
// ==UserScript==
// @name New Userscript
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match www.reddit.com/r/some-subreddit
// @grant none
// ==/UserScript==
(function() {
'use strict';
$( "textarea" ).one("click",(function() {
$(".usertext-edit").prepend ( `
<div id="gmSomeID"><ul id="gmSomeeID"><a href="#stickers1"</a> <a href="#stickers2"</a> <a href="#stickers3"</a> <a href="#stickers4"</a> <a href="#stickers5"</a ><a href="#stickers6"</a> <a href="#stickers7"</a> <a href="#stickers1"</a> <a href="#stickers2"</a> <a href="#stickers3"</a> <a href="#stickers4"</a> <a href="#stickers5"</a> <a href="#stickers6"</a>
</ul></div>
` );
$('ul#gmSomeeID').css({
'overflow-y':'scroll',
'display':'block',
'overflow-wrap' : 'normal',
'height':'100px',
'background-color':'white'
});
$('ul#gmSomeeID a').click(function(){
$("this").closest("div.usertext-edit")
.find("textarea")
.val($("this")
.closest("div.usertext-edit")
.find("textarea")
.val() +' '+ '[](' + this.getAttribute('href') + ') ');
});
}));
})();
还可以尝试事件委派:
$(function(){
//Your code here
})
注意1:由于DOM已完全加载,因此代码在控制台中工作。
注2:应改为$('this')
而不是此.getAttribute('href')
,最好使用$(this).attr('href')
希望这会有所帮助。当您在控制台中尝试代码时,DOM已经完成了构建。如果您拥有所显示的代码,则在文件中的所有HTML之前,它将尝试在元素解析到内存之前查找元素
将代码放在文档中。就绪处理程序:
$(function(){
$('body').on('click', '#test a', function(){
$(this).closest('parent').find('textarea').val( $(this).attr('href') );
});
});
请发布我们复制您的问题所需的最少代码(HTML、CSS、JavaScript)。然后将您的代码放入ready函数中。&关于那些说将其放入文档准备就绪的人,我认为tampermonkey脚本会在页面创建后运行?
$(function(){
$('ul#test a').click(function(){
$('this').closest('parent').find('textarea').val(this.getAttribute('href'));
});
});