我有一个与此内容相关的文本区域
<textarea id="testContent"> <img src="..." alt="value"> My text.... </textarea>
我知道我可以使用javascript选择仅img标签的alt值,如图所示
<script>
var $textfeldVal = document.getElementById("testContent");
$img = $textfeldVal.getElementsByTagName("img")[0];
alert("ALT VALUE: "+$img.alt);
</script>
有没有一种方法可以使用javascript选择alt值<img>
以及textarea中的文本?
好吧,如果必须的话,可以像这样将它们连接起来:
var $textarea = $("textarea#testContent"),
textareaValue = $textarea.val(),
// get alt value using regex, as jQuery can't find DOM nodes within a textarea
altValueMatch = textareaValue.match(/\<img.*?alt=(\"|\')(.*?)\1.*?\>/),
altValue = (Array.isArray(altValueMatch) && typeof altValueMatch[2] === "string")
? altValueMatch[2]
: null;
// remove the img tag from textareaValue and trim any trailing whitespace
textareaValue = textareaValue.replace(/\<img.*?\>/, "").trim();
var concatenated = [altValue, textareaValue].join(" ");
但是,您实际上不应该将DOM节点放在文本区域内,因为它仅用于纯文本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句