如何在HTML / Javascript中返回图像的值

时间:2018-06-20 09:49:41

标签: javascript html

<p id="resultado"></p>
    <img src="Imagens/R5.jpg" id="P1" class="P1" value="R5" onclick="pergunta1()" style="width:164px;height:164px;">
    <img src="Imagens/R2.jpg" id="P1" class="P1" value="R2" onclick="pergunta1()" style="width:163px;height:163px;">
    <img src="Imagens/R8.jpg" id="P1" class="P1" value="R8" onclick="pergunta1()" style="width:163px;height:163px;">

我希望它返回我的图像的值然后将其隐藏,但是它甚至不返回任何值,我也在使用JQuery以便隐藏同一个类的所有图像

<script type="text/javascript">

    function pergunta1(){

    var p1 = document.getElementById('P1');
        if (p1.value == "R5"){
            return "N1_5"
        }
        else if (p1.value == "R2"){
            return "N1_2"
        }
        else{
            return "N1_8"
        }
        $('.P1').hide();
    }
    document.getElementById("resultado").innerHTML = myFunction();

</script>

2 个答案:

答案 0 :(得分:0)

  

Blockquote

最好只使用一种脚本语言,尽量不要混合使用它并了解更多信息。这是您想要的代码。

<!DOCTYPE html>
<html>
<body>

<p id="resultado"></p>
    <img src="Imagens/R5.jpg" id="P1" class="P1" value="R5" onclick="pergunta1(this)" style="width:164px;height:164px;">
    <img src="Imagens/R2.jpg" id="P2" class="P1" value="R2" onclick="pergunta1(this)" style="width:163px;height:163px;">
    <img src="Imagens/R8.jpg" id="P3" class="P1" value="R8" onclick="pergunta1(this)" style="width:163px;height:163px;">

<script>

    function pergunta1(element){

    
    var res="";
        if (element.getAttribute("value") == "R5"){
            res= "N1_5"
        }
        else if (element.getAttribute("value") == "R2"){
            res="N1_2"
        }
        else{
            res ="N1_8"
        }
        element.style.display = "none";
        document.getElementById("resultado").innerHTML =res;
    }
    
</script>
</body>
</html>

答案 1 :(得分:0)

您需要在函数内移动 P resultado 以显示所选值

function pergunta1(){
    var valor = $(event.target).attr("value");
    var resultado;

        if (valor == "R5"){
            resultado = "N1_5"
        }
        else if (valor == "R2"){
            resultado = "N1_2"
        }
        else{
            resultado = "N1_8"
        }
        $('.P1').hide();  
        $("#resultado").html(resultado);
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="resultado"></p>
    <img src="Imagens/R5.jpg" id="P1_Imagen1" class="P1" value="R5" onclick="pergunta1()" style="width:164px;height:164px;">
    <img src="Imagens/R2.jpg" id="P1_Imagen2" class="P1" value="R2" onclick="pergunta1()" style="width:163px;height:163px;">
    <img src="Imagens/R8.jpg" id="P1_Imagen3" class="P1" value="R8" onclick="pergunta1()" style="width:163px;height:163px;">
</p>