jQuery 在控制台中工作,但不在 .js 文件中 [英] jQuery works in console but not in .js file
问题描述
$('ul#test a').click(function(){
$('this').closest('parent').find('textarea').val(this.getAttribute('href'));
});
适用于 Google Chrome
片段,但未加载 Tampermonkey
.
我认为它甚至在找到目标之前就试图设置一个值
works in Google Chrome
snippet but not loaded with Tampermonkey
.
I think that it's trying to set a value before even finding the target
(编辑)整个脚本:
// ==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') + ') ');
});
}));
})();
它在文本区域上方显示一些图片,我试图让它在点击它们时将它们插入到所述文本区域
It displays some pictures above textarea's and I'm trying to make it insert them in the said textarea when they're clicked on
推荐答案
把你的代码放在 ready
函数中,这样事件就会在你的选择器中找到元素,因为它会在完全加载后立即执行DOM 的:
Put your code inside ready
function so the event will find the element in your selector since it will be executed just after the full load of the DOM :
$(function(){
//Your code here
})
也试试事件委托:
$(function(){
$('body').on('click', '#test a', function(){
$(this).closest('parent').find('textarea').val( $(this).attr('href') );
});
});
注意 1: 由于 DOM 已完全加载,因此代码在控制台中有效.注意 2: $('this')
应该是 $(this)
而不是 &使用 $(this).attr('href')
而不是 this.getAttribute('href')
会更好.
NOTE 1: The code works in the console because the DOM was fully loaded.
NOTE 2: The $('this')
should be $(this)
instead & it will be better to use $(this).attr('href')
rather than this.getAttribute('href')
.
希望这会有所帮助.
这篇关于jQuery 在控制台中工作,但不在 .js 文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!