在Asp.net页面上交换图像

时间:2016-03-11 15:23:38

标签: javascript html asp.net

我正在尝试交换前/后onclick()的图片。当我点击图像时,我可以看到后方图像,但是当我点击后方图像时,我看不到前方。我从服务器代码传递前后路径:

<script>


var theImg = null, theImgPath = null;

window.addEventListener("load", function () {
    theImg = document.getElementById("imgCh_Front");
    theImgPath = theImg.getAttribute("src");
});

function changeImage(front, rear) {
    if (theImgPath === front) {
        alert("1");
        theImg.src = rear;
        alert("2");
    } else if (theImgPath === rear) {
        alert("3");
        theImg.src = front;
        alert("4");
    } else {
        alert("else..");
    }
}

HTML

<div class="pic_box">
                    <img 
                        onclick="changeImage('<%#  GetFileURL(Eval("ImageFront"))%>', '<%#  GetFileURL(Eval("ImageRear"))%>')" 
                        id="imgCh_Front" alt="" class="ImageCh" src='<%# GetFileURL(Eval("ImageFront"))%>' />
                    <div class="ico">
                        <span class="fa fa-photo"></span>
                    </div>
                    <div class="shade"></div>
                </div>

功能

 Public Shared Function GetFileURL(fileID As String) As String
        Dim fileInfo = GetFile(Convert.ToInt32(fileID))
        ' return a bad or default image url as appropriate
        If fileInfo Is Nothing Then
        Else
            Return GetUrl(fileInfo)
        End If
    End Function

1 个答案:

答案 0 :(得分:2)

此代码修复了您遇到的两个问题,即在一种情况下没有获取图像的来源而不是比较源,而是在另一个中分配源。

它还会删除重复调用以查找图像的src:

<script>


    var theImg = null, theImgPath = null; 

    window.addEventListener("load", function(){
         theImg = document.getElementById("imgCheque_Front");
    });

    function changeImage(front, rear) {

        theImgPath = theImg.getAttribute("src");

        if (theImgPath  === front) {
            theImg.src = rear;
        } else if (theImgPath  === rear) {
            theImg.src = front;
        } else {
            alert("else..");
        }
    }
</script>

顺便说一句,您的服务器端代码存在一些问题:

' The function is declared as returning a String
Public Shared Function GetFileURL(fileID As String) As String

    ' But here, your Dim doesn't have an "As" clause, which
    ' indicates that your are not working with Option Explicit
    ' and/or Option Strict turned on (very bad).

    ' What type does GetFile return? That's the type that fileInfo
    ' should be declared as.
    Dim fileInfo As ??? = GetFile(Convert.ToInt32(fileID))

    ' Here, you have an if/else with an empty true branch (not
    ' a good convention):
    If fileInfo Is Nothing Then
    Else
        Return GetUrl(fileInfo)
    End If

    ' How about this instead of all that above code:
    If Not GetFile(Convert.ToInt32(fileID)) Is Nothing Then
        Return GetUrl(fileInfo)
    End If

End Function