如何在jQuery变量中操作HTML? [英] How to manipulate HTML within a jQuery variable?

查看:174
本文介绍了如何在jQuery变量中操作HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理jQuery变量中存储的HTML.我想在将变量写入文档之前进行此操作.

I am trying to manipulate the HTML stored within a jQuery variable. I want to do this manipulation before I write the variable to the document.

所以,我有一个变量定义为:

So, I have a variable defined as:

var sighting = "<div><span class="feed_name"></span></div>";

我想在"span"元素中放入"hello world".这是我无法工作的部分:

And I want to put "hello world" in the span element. This is the part that I can't get to work:

$(sighting).("span.feed_name").html(name);

然后我将'sighting'变量写入页面:

Then I write the 'sighting' variable to the page:

$(#sightings).append(sighting);

将HTML中的瞄准变量放入页面上的<div id="sightings"></div>元素中.

Which puts the HTML in the sighting variable into the <div id="sightings"></div> element on the page.

任何帮助将不胜感激!

谢谢

标记

推荐答案

我更喜欢这种方法,您将对元素有更多的控制权,因为它们保留为对象,因此更易于强制转换为函数.

I prefer this method, you'll have more control over the elements because they remain as objects, and are thus easier to coerce into functions.

sighting = document.createElement('div');

然后,您可以像对待DOM一样将其处理

Then you can manipulate as if it was already part of the DOM

$(sighting).addClass("feed_name").html(name);
$(sighting).appendTo("#sighting");

编辑

嗯...看来我误解了你的问题.我仍然希望使用createElement()函数制作元素.

Hmm... it seems I misread your question. I would still prefer to make the elements using the createElement() function.

sighting = document.createElement('div');
sighting_contents = document.createElement('span');

$(sighting_contents).addClass("feed_name").html(name);
$(sighting).append(sighting_contents);
$(sighting).appendTo("#sightings");

更详细一些,但是如果您愿意,您可以将最后三个字符串串成一长行...我认为这更具可读性,并最终为您提供了更多的控制权,因为从技术上讲,您不应该编写大量HTML在您的js中,您可以创建元素并附加它们,但是就编写大的标记块而言,我认为将元素创建为这样的对象可以为您提供更大的灵活性.

A little more verbose, but you can string the last three into one long line if you want... I think this is more readable and ultimately gives you more control, because technically you shouldn't be writing a bunch of HTML in your js, you can create the elements and append them, but as far as writing big blocks of markup I think creating the elements as objects like this gives you more flexibility.

您还可以通过以下更简单的方式将事件附加到这样添加的元素上:

You can also attach events to elements added like this in a more simple way:

$(sighting).bind("click", function(event) {
  $(this).fadeOut();
});

这篇关于如何在jQuery变量中操作HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆