Home  >  Article  >  Web Front-end  >  How to convert string into jquery object

How to convert string into jquery object

零到壹度
零到壹度Original
2018-03-26 15:24:592097browse

This time I will explain in detail how to convert a string into a jquery object, and what are the precautions for converting a string into a jquery object. The following is a practical case, let's take a look.

jQuery(test)[0].outerHTMLouterHTML
是部分浏览器提供的原生DOM属性,可返回包括元素本身在内的html代码。
如果不需要标签本身,可用jQuery的html方法来获取html文本
jQuery(test).html()
var test=&#39;<p>.<img src="oldsrc" />.</p>&#39;
var jObj=$(test);
var imgs=jObj.find(&#39;img&#39;);
imgs.each(function(){
  $(this).attr(&#39;src&#39;,&#39;newsrc&#39;);
  });
test=jObj[0].outerHTML;
或者
test=&#39;<p>&#39;+jObj.html()+&#39;</p>&#39;;
这里只能用DOM片断来做,无法带上html

Or you can directly use regular expressions to replace

&#39;<p><img src="oldsrc" /></p>&#39;.replace(
/<img(\s+[^>]*)src="([^"]+)"([^>]*)>/ig,
function(a,b,c,d){    //这里a代码匹配到的一个img元素的整个字符串,b代码第一个括号内的内容,c代码第二个括号的内容,就是img的src,d代码后面的内容
//这里可以处理下c再连接,也可以直接写新的src
return &#39;<img&#39;+b+&#39;src="&#39;+&#39;new src&#39;+&#39;"&#39;+d+&#39;>&#39;;
})

or like this:

var a=&#39;<p>123</p>&#39;;
var jObj=$(a);
console.log($(&#39;<input></input>&#39;))

Related recommendations:

How to convert html string into Jquery object or Dom object in JavaScript

Conversion between json string and object-javascript/jQuery

Convert jQuery object into ordinary string

The above is the detailed content of How to convert string into jquery object. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn