javascript 使用 jQuery 在 div 标签内添加一些字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11871100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:37:02  来源:igfitidea点击:

Add some string inside div tag using jQuery

javascriptjquery

提问by Jhonny Jr.

I'm just trying to add some string or HTML tag inside div #OL_Icon_63using jQuery .append(), here's the example of code :

我只是想#OL_Icon_63使用 jQuery在 div 中添加一些字符串或 HTML 标签.append(),这是代码示例:

$(document).ready(function() {
    $('#OL_Icon_63').append('HELLO WORLD');
});

But that's code won't work for me, I try to change the code like this :

但那是代码对我不起作用,我尝试像这样更改代码:

$(document).ready(function() {
    $("body").click(function() {
       $('#OL_Icon_63').append('HELLO WORLD');
    });
});

And

$(document).ready(function() {
    $("body").hover(function() {
       $('#OL_Icon_63').append('HELLO WORLD');
    });
});

Two kinds of code work for me where I use .hover()and .click()after body tag, but i basically can not use the function like .append() or anything else without adding .hover() or .click() after $("body") but when I use click or hover the string appeared repeatedly

两种代码对我有用.hover(),在我使用的地方和.click()在 body 标签之后,但我基本上不能使用像 .append() 或其他任何东西而不在 $("body") 之后添加 .hover() 或 .click() 但是当我使用单击或悬停时,字符串重复出现

Can anyone give me some example / opinion so that .append()jQuery function will work perfect for me?

谁能给我一些例子/意见,以便.append()jQuery 函数对我来说很完美?

采纳答案by Benjamin Gruenbaum

A more general solution is using the fact javascript functions are objects, once the function clickAction is called it will set itself to a blank function after appending the text

一个更通用的解决方案是使用 JavaScript 函数是对象这一事实,一旦调用 clickAction 函数,它会在附加文本后将自身设置为一个空白函数

EDITThis does not work in jQuery due to the way it handles events, however it does contain a method called one()

编辑由于它处理事件的方式,这在 jQuery 中不起作用,但它确实包含一个名为 one() 的方法

$(document).ready(function() {
  var clickAction = function(){
     $('div').append("Hello World");
  } 
    $("div").one("click",clickAction);
});?

回答by Isaac Gonzalez

why don't you try without $(document).readythis works for me:

你为什么不试试没有$(document).ready这个对我有用:

(function(){
    $('#OL_Icon_63').append('HELLO WORLD');
})();

Working example: http://jsfiddle.net/tgzKQ/

工作示例:http: //jsfiddle.net/tgzKQ/

回答by Austin

Use textinstead:

使用text来代替:

$('#OL_Icon_63').text("hello world")

You are using append incorrectly. Append is for adding elementsto the innerHTML of an element. textis for text, and htmlis for HTML

您使用的 append 不正确。Append 用于将元素添加到元素的innerHTML。text用于文本,html用于 HTML

This will also replace all text in the element, so there will be no multiples.

这也将替换元素中的所有文本,因此不会有倍数。