[英]Converting the content in the textbox to the HTML
我正在一个项目中,将HTML代码复制到<textarea>
,我需要在其中获取值...
例如, <img alt="hello">
是我粘贴到<textarea>
。 当我单击按钮时,我需要搜索<img>
标记,并且需要获取alt属性的值“ hello”。 这是我正在使用的代码段。
<textarea rows="6" id="t">
there is no
love in the ghetto
img
<img alt="hello">
so come here
and get it
</textarea>
<input type="button" id="getline" value="get line" />
上面是HTML代码。
这是我用来搜索和查找alt属性值的脚本。
<script type="text/javascript">
$(document).ready(function(){
$("#getline").click(function(){
var str = $("#t").html();
var srres= str.match(/img/gi);
for(i=0;i<srres.length;i++)
{
var atim= $(""+srres[i]).attr("alt");
alert(atim);
}
});
});
</script>
但是我得到的警报未定义。
任何人都可以在这方面帮助我。 这对我会有所帮助。
使用val()
获取文本区域的值,而不是html()
然后,您可以将该html字符串包装在jQuery对象中,并使用jQuery方法而不是regex来获取所需的内容
$("#getline").click(function(){
var $div = $('<div>').html( $("#t").val() );
$div.find('img').each(function(){
console.log( this.alt);
});
});
您几乎在那里-仅需要val()
而不是html()
即可从textarea中获取文本:
$(document).ready(function() { $("#getline").click(function() { var str = $("#t").val(); console.log(str); var srres = str.match(/img/gi); for (i = 0; i < srres.length; i++) { var atim = $("" + srres[i]).attr("alt"); alert(atim); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img alt="hello">is the content which i paste in to the textarea, when i click a button i need to search for "img" and i need to fetch the value of alt attribute that is "hello". Here is the snippet I'm using. <textarea rows="6" id="t"> there is no love in the ghetto img <img alt="hello">so come here and get it </textarea> <input type="button" id="getline" value="get line" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.