这会按预期记录10个textarea
元素中每个元素的值:
$('.container').each(function() {
var textA = $('textarea', this).val();
console.log(textA)
});
这个正则表达式在控制台中运行良好:
"https://hi.com/hey junk nothing https://hi.com/there".match(/https:\/\/hi\.com\/[A-Za-z_]{1,15}/ig);
我回来了:["https://hi.com/hey", "https://hi.com/there"]
但是当我尝试这个时:
$('.container').each(function() {
var textA = $('textarea', this).val();
var matches = textA.match(/https:\/\/hi\.com\/[A-Za-z_]{1,15}/ig);
console.log(matches)
});
我得到Uncaught TypeError: Cannot read property 'match' of undefined
为什么undefined
?是因为Type
所涉及的match
未被正确宣布?如果是这样,我该怎么声明才能“看到”?
答案 0 :(得分:1)
要回答这个问题:您需要检查textarea
中是否存在.container
。您可以使用.length > 0
:
$('.container').each(function() {
var textArea = $('textarea', this); // Changed here
if (textArea.length > 0) { // and here
var textA = textArea.val();
var matches = textA.match(/https:\/\/hi\.com\/[A-Za-z_]{1,15}/ig);
console.log(matches);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<textarea name="mytextarea" id="" cols="30" rows="10">
https://hi.com/new-url
More
lines
https://hi.com/last-url
</textarea>
</div>
<div class="container">
Empty one with no textarea
</div>