0

I have a function where I want to read the length of the path of a image source and use it in an if else clause but the variable which it is supposed to contain the numeric value seems empty. Neither the if clause nor the else one is being used.

<!DOCTYPE html>
<html>
<head>
<script>
function imgresize(img){
var strl=img.src.length;
  if(strl<10)
  {
    //do someting
  }
  else
    //do something
}
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
   <img onclick="imgresize(this)" src="image1.png">
</body>
</html>

Any idea why this strl variable is not being filled?

4

2 回答 2

1

尝试这个 :

在这里生活小提琴

HTML

<img src="http://cdn1.iconfinder.com/data/icons/musthave/256/Positive.png" alt="etstst" onclick="imgresize(this);">
<img src="zzzz" alt="etstst" onclick="imgresize(this);">

jQuery

function imgresize(img) {
    var stringlen =  $(img).attr('src').length;
    alert("length is : " + stringlen);
    if (stringlen < 10) {
        alert("Length smaller than 10");
    } else{
        alert("Length greater than 10");
    }
}
于 2013-03-24T15:51:01.020 回答
1

试试这个:

http://jsfiddle.net/aidioo7/Fg3CB/

JS代码:-

function imgresize(img) {
    var strl = img.src.length;
    if (strl < 10) {
        alert("Length smaller than 10");
    } else{
        alert("Length greater than 10");
    }
}

HTML 代码:-

<img src="http://t2.gstatic.com/images?q=tbn:ANd9GcQTkCsSOSfmGx9uq2EvOeq65-oZBlIzvqSKnqgNgrDEsPn1b7xr" alt="etstst" onclick="imgresize(this);">
于 2013-03-24T13:19:28.597 回答