Is there a better way to write this. I'm checking the input of a textarea and trying to find if it contains an object or iframe tags, if not then set var x =1
if ($textareaval.find('iframe').length > 0) {
ale开发者_开发问答rt('iframe')
} else if ($textareaval.find('param').length > 0) {
alert('object')
} else {
var x = 1;
alert(x)
i think even you don't need to check length > o.. do like this..
if ($textareaval.has('iframe, param').length) {
alert('iframe, param')
}else{var x=1;}
Observing that you will only be giving one alert, and therefore assuming that you will only encounter one type, I suggest the following:
var foundItems = $textareaval.has('iframe, param');
var alertVal = 1;
if(foundItems.length){
alertVal = "object";
if(foundItems[0].tagName == "iframe")
alertVal = "iframe";
}
alert(alertVal);
This has the advantage of only one traversal and minimal short-circuit logic utilizing the most common properties of the two objects tested. And, it's readable.
Note: the foundItems.length test is NOT testing for existence, as this property will always exist on a javascript collection; but, if it evaluates to 0, that is a false - and any other number is not.
If you don't care which one it has you could combine the two checks into one:
if ($textareaval.has('iframe, param').length > 0) {
x = 1;
}
Edit: You say you do care, though, so then no. Your code is fine, no improvement needed.
精彩评论