在生成的ajax表中单击tr行后打开div弹出窗口

时间:2013-09-13 13:17:02

标签: javascript php jquery html ajax

使用AJAX生成表后,我的javascript出现问题。 我正在生成一个用户插入值的表。从本地运行的SQL EXPRESS 2012数据库中检索值。检索到值后,它们将存储在字符串中。该字符串将被发送回index.thml。所有结果检索都由validate.php完成。

我用普通的表尝试了我的代码,它就像一个魅力。但每当我使用生成的表时,似乎拒绝运行javascript。

我个人对此的想法是因为加载页面时表不存在。在加载页面后创建表,导致javascript无法正常运行。鼠标悬停时突出显示行时出现同样的问题。我通过在tr.mouseover中调用mouseover函数来克服这个问题。

说实话,我是ajax和javascript的新手,所以我现在几乎所有的东西都来自互联网。我知道一切意味着什么,并改变了我的项目的代码。我真的希望你们能够对此发出强烈的光芒,因为我已经被困了好几天了。

让我们开始吧:

我的index.html:

<html>
<head>
    <title>ESL Checking Tool</title>
    <link href="style/style.css" rel="stylesheet" type="text/css" media="all" />
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="ajaxrequest.js"></script>
    <script type="text/javascript">
        function callAjax(method, value, target)
        {
            if(encodeURIComponent) 
            {
                var req = new AjaxRequest();
                var params = "method=" + method + "&value=" + encodeURIComponent(value) + "&target=" + target;
                req.setMethod("POST");
                req.loadXMLDoc('validate.php', params);
            }
        }
    </script>
    <script type="text/javascript">
        function mouseover() 
        {
            var message = $('#message');
            var tr = $('#table_id').find('tr');

            tr.hover(
                function() 
                {  //mouseover
                    $(this).addClass('row-highlight');
                    var values = '';
                    var tds = $(this).find('td');

                    $.each(tds, function(index, item) 
                    {
                        values = values + 'td' + (index + 1) + ':' + item.innerHTML + '<br/>';
                    });
                    message.html(values);
                },
                function() 
                {  // mouseout
                    $(this).removeClass('row-highlight');
                    message.html('');
                })
        }
    </script>
    <script type="text/javascript" src="js/script.js"></script>
</head>

<body id="dt_example">
<form method="POST" action="non-Ajax form handler" onsubmit="return checkForm(this;">
    <fieldset>
        <legend>ESL Checkup Form</legend>

        <p>Product: <input type="text" size="32" id="product" name="product" onkeyup="if(this.value != '') callAjax('checkProduct', this.value, this.id);">
        <input id="valid_product" type="checkbox" disabled name="valid_product"></p>
        <div id="rsp_product">
        </div>

        <p>Barcode: <input type="text" size="32" id="barcode" name="barcode" onkeyup="if(this.value != '') callAjax('checkBarcode', this.value, this.id);">
        <input id="valid_barcode" type="checkbox" disabled name="valid_barcode"></p>
        <div id="rsp_barcode"><!-- --></div>

        <p>ESL: <input type="text" size="32" id="email" name="email" onkeyup="if(this.value != '') callAjax('checkEmail', this.value, this.id);">
        <input id="valid_email" type="checkbox" disabled name="valid_email"></p>
        <div id="rsp_email"><!-- --></div>
    </fieldset>
</form>

<div id="message">
</div>
<a href="#" class="topopup">Click Here Trigger</a>
<div id="toPopup"> 
    <div class="close"></div>
    <span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
    <div id="popup_content"> <!--your content start-->
        <p>
        Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, 
        feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi 
        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, 
        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique 
        senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, 
        feugiat vitae, ultricies eget, tempor sit amet, ante. </p>
        <br />
        <p>
        Donec eu libero sit amet quam egestas semper. Aenean ultricies mi 
        vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, 
        commodo Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. </p>
        <p align="center"><a href="#" class="livebox">Click Here Trigger</a></p>
    </div> <!--your content end-->

</div> <!--toPopup end-->

<div class="loader"></div>
<div id="backgroundPopup"></div>
</body>
</html>

我的风格/ style.css:

/* 
author: istockphp.com
*/
#backgroundPopup { 
z-index:1;
position: fixed;
display:none;
height:100%;
width:100%;
background:#000000; 
top:0px;  
left:0px;
}
#toPopup {
font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
background: none repeat scroll 0 0 #FFFFFF;
border: 10px solid #ccc;
border-radius: 3px 3px 3px 3px;
color: #333333;
display: none;
font-size: 14px;
left: 50%;
margin-left: -402px;
position: fixed;
top: 20%;
width: 800px;
z-index: 2;
}
div.loader {
background: url("../img/loading.gif") no-repeat scroll 0 0 transparent;
height: 32px;
width: 32px;
display: none;
z-index: 9999;
top: 40%;
left: 50%;
position: absolute;
margin-left: -10px;
}
div.close {
background: url("../img/closebox.png") no-repeat scroll 0 0 transparent;
bottom: 24px;
cursor: pointer;
float: right;
height: 30px;
left: 27px;
position: relative;
width: 30px;
}
span.ecs_tooltip {
background: none repeat scroll 0 0 #000000;
border-radius: 2px 2px 2px 2px;
color: #FFFFFF;
display: none;
font-size: 11px;
height: 16px;
opacity: 0.7;
padding: 4px 3px 2px 5px;
position: absolute;
right: -62px;
text-align: center;
top: -51px;
width: 93px;
}
span.arrow {
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 7px solid #000000;
display: block;
height: 1px;
left: 40px;
position: relative;
top: 3px;
width: 1px;
}
div#popup_content {
margin: 4px 7px;
}
.row-highlight {
background-color: #0099FF;
}

我的ajaxrequest.js:

function AjaxRequest()
{
    var req;
    var method="GET";
    var nocache=false;
    var handler;
    this.loadXMLDoc=function(url,params)
        {
            if(window.XMLHttpRequest)
            {
                    try
                    {
                        req=new XMLHttpRequest();
                    }
                    catch(e)
                    {
                        req=false;
                    }
            }
            else if(window.ActiveXObject)
            {
                try
                {
                    req=new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e)
                {
                    try
                    {
                        req=new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch(e)
                    {
                        req=false;
                    }
                }
            }
            if(req)
            {
                if(!handler)handler=processReqChange;req.onreadystatechange=handler;if(nocache)
                {
                    params+=(params!='')?'&'+(new Date()).getTime():(new Date()).getTime();
                }
                if(method=="POST")
                {
                    req.open("POST",url,true);
                    req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    req.send(params);
                }
                else
                {
                    if(params)url+="?"+ params;req.open(method,url,true);req.send(null);
                }
            return true;
            }
        return false;
        }
        this.setMethod=function(newmethod)
        {
            method=newmethod.toUpperCase();
        }
        this.nocache=function()
        {
            nocache=true;
        }
        this.setHandler=function(fn)
        {
            handler=fn;
        }
        this.getResponse=function()
        {
            return req;
        }
        var getNodeValue=function(parent,tagName)
        {
            var node=parent.getElementsByTagName(tagName)[0];
            return(node&&node.firstChild)?node.firstChild.nodeValue:'';
        }
        var processReqChange=function()
        {
            if(req.readyState==4&&req.status==200)
            {
                var response=req.responseXML.documentElement;
                var commands=response.getElementsByTagName('command');
                for(var i=0;i<commands.length;i++)
                {
                    method=commands[i].getAttribute('method');
                    switch(method)
                    {
                        case'alert':var message=getNodeValue(commands[i],'message');
                        window.alert(message);
                        break;
                        case'setvalue':var target=getNodeValue(commands[i],'target');
                        var value=getNodeValue(commands[i],'value');
                        if(target&&value!=null)
                        {
                            document.getElementById(target).value=value;
                        }
                        break;
                        case'setdefault':var target=getNodeValue(commands[i],'target');
                        if(target)
                        {
                            document.getElementById(target).value=document.getElementById(target).defaultValue;
                        }
                        break;
                        case'focus':var target=getNodeValue(commands[i],'target');
                        if(target)
                        {
                            document.getElementById(target).focus();
                        }
                        break;
                        case'setcontent':var target=getNodeValue(commands[i],'target');
                        var content=getNodeValue(commands[i],'content');
                        if(target&&(content!=null))
                        {
                            document.getElementById(target).innerHTML=content;
                        }
                        break;
                        case'setstyle':var target=getNodeValue(commands[i],'target');
                        var property=getNodeValue(commands[i],'property');
                        var value=getNodeValue(commands[i],'value');
                        if(target&&property&&(value!=null))
                        {
                            document.getElementById(target).style[property]=value;
                        }
                        break;
                        case'setproperty':var target=getNodeValue(commands[i],'target');
                        var property=getNodeValue(commands[i],'property');
                        var value=getNodeValue(commands[i],'value');
                        if(value=="true")value=true;
                        if(value=="false")value=false;
                        if(target&&document.getElementById(target))
                        {
                            document.getElementById(target)[property]=value;
                        }
                        break;
                        default:window.console.log("Error: unrecognised method '"+ method+"' in processReqChange()");
                    }
                }
            }
        }
}

my script.js:

/* 
author: istockphp.com
*/
jQuery(function($) {

$("a.topopup").click(function() {
        loading(); // loading
        setTimeout(function(){ // then show popup, deley in .5 second
            loadPopup(); // function show popup 
        }, 500); // .5 second
return false;
});

$("tr#row-clck").click(function() {
        loading(); // loading
        setTimeout(function(){ // then show popup, deley in .5 second
            loadPopup(); // function show popup 
        }, 500); // .5 second
return false;
});

/* event for close the popup */
$("div.close").hover(
                function() {
                    $('span.ecs_tooltip').show();
                },
                function () {
                    $('span.ecs_tooltip').hide();
                }
            );

$("div.close").click(function() {
    disablePopup();  // function close pop up
});

$(this).keyup(function(event) {
    if (event.which == 27) { // 27 is 'Ecs' in the keyboard
        disablePopup();  // function close pop up
    }   
});

$("div#backgroundPopup").click(function() {
    disablePopup();  // function close pop up
});

$('a.livebox').click(function() {
    alert('Hello World!');
return false;
});


 /************** start: functions. **************/
function tablerowclick() {
    loading(); // loading
    setTimeout(function(){ // then show popup, deley in .5 second
        loadPopup(); // function show popup 
        }, 500); // .5 second
return false;
}

function loading() {
    $("div.loader").show();  
}
function closeloading() {
    $("div.loader").fadeOut('normal');  
}

var popupStatus = 0; // set value

function loadPopup() { 
    if(popupStatus == 0) { // if value is 0, show popup
        closeloading(); // fadeout loading
        $("#toPopup").fadeIn(0500); // fadein popup div
        $("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8
        $("#backgroundPopup").fadeIn(0001); 
        popupStatus = 1; // and set value to 1
    }   
}

function disablePopup() {
    if(popupStatus == 1) { // if value is 1, close popup
        $("#toPopup").fadeOut("normal");  
        $("#backgroundPopup").fadeOut("normal");  
        popupStatus = 0;  // and set value to 0
    }
}
/************** end: functions. **************/
}); // jQuery End

我的validate.php:

<?PHP
// check that all POST variables have been set
if(!isset($_POST['method']) || !$method = $_POST['method']) exit;
if(!isset($_POST['value']) || !$value = $_POST['value']) exit;
if(!isset($_POST['target']) || !$target = $_POST['target']) exit;

$serverName = "localhost\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"MIQ", "UID"=>"sa", "PWD"=>"miq123");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
}else{
   echo "Connection could not be established.<br />";
   die( print_r( sqlsrv_errors(), true));
}

$passed = false;
$retval = '';

switch($method)
{
    case 'checkProduct':
    $query = "SELECT PRODUCT_NAME, ESL, Product FROM ESL, SIQEE_IM_ITEM_INFORMATION WHERE ESL.Product = SIQEE_IM_ITEM_INFORMATION.GTIN AND SIQEE_IM_ITEM_INFORMATION.PRODUCT_NAME LIKE '%$value%'";
    //Execute query
    $qry_result = sqlsrv_query($conn, $query, array(), array("Scrollable"=>"buffered")) or die(sqlsrv_error());
    //Build Result String
    $display_string = '<table cellpadding="0" cellspacing="0" border="0" class="display" id="table_id" width="60%">';
    $display_string .= "<thead>";
    $display_string .= "<tr>";
    $display_string .= "<th>ESL</th>";
    $display_string .= "<th>Barcode</th>";
    $display_string .= "<th>Product</th>";
    $display_string .= "</tr>";
    $display_string .= "</thead>";
    $display_string .= "<tbody>";

    // Insert a new row in the table for each person returned
    while($row = sqlsrv_fetch_array($qry_result)){
    $display_string .= "<tr id='row-clck' onmouseover='mouseover();'>";
    $display_string .= "<td>$row[ESL]</td>";
    $display_string .= "<td>$row[Product]</td>";
    $display_string .= "<td>$row[PRODUCT_NAME]</td>";-
    $display_string .= "</tr>";

    }
    $display_string .= "</tbody>";
    $display_string .= "</table>";
    $num_results = sqlsrv_num_rows($qry_result); 
    if ($num_results > 0){
        $retval = $display_string;
        $passed = true;
    }
    else{
    $retval = "Dit product is nog niet gekoppeld";
    $passed = false;
    }
      // ...
    // set the $retval message, and the $passed variable to true or false
    // ...
    break;

    case 'checkBarcode':
    $query = "SELECT PRODUCT_NAME, ESL, Product FROM ESL, SIQEE_IM_ITEM_INFORMATION WHERE ESL.Product = '$value' AND SIQEE_IM_ITEM_INFORMATION.GTIN = '$value'";
    //Execute query
    $qry_result = sqlsrv_query($conn, $query, array(), array("Scrollable"=>"buffered")) or die(sqlsrv_error());
    //Build Result String
    $display_string = "<table>";
    $display_string .= "<tr>";
    $display_string .= "<th>ESL</th>";
    $display_string .= "<th>Barcode</th>";
    $display_string .= "<th>Product</th>";
    $display_string .= "</tr>";

    // Insert a new row in the table for each person returned
    while($row = sqlsrv_fetch_array($qry_result)){
    $display_string .= "<tr>";
    $display_string .= "<td>$row[ESL]</td>";
    $display_string .= "<td>$row[Product]</td>";
    $display_string .= "<td>$row[PRODUCT_NAME]</td>";-
    $display_string .= "</tr>";

    }
    $display_string .= "</table>";
    $num_results = sqlsrv_num_rows($qry_result); 
    if ($num_results > 0){
        $retval = $display_string;
        $passed = true;
    }
    else{
    $retval = "Deze barcode is nog niet gekoppeld";
    $passed = false;
    }
    // ...
    // set the $retval message, and the $passed variable to true or false
    // ...
    break;
    case 'checkAge':
    if ($value >= 16 && $value <= 100){
    $retval = "is helemaal goed";
    $passed = true;
    }
    else{
    $retval = "Nope no can do";
    $passed = false; 
    }
    // ...
    // set the $retval message, and the $passed variable to true or false
    // ...
    break;

    case 'checkEmail':
    //build query
            $query2 = "SELECT PRODUCT_NAME, ESL, Product FROM ESL, SIQEE_IM_ITEM_INFORMATION WHERE ESL.ESL = '$value' AND SIQEE_IM_ITEM_INFORMATION.GTIN = ESL.Product";
    //Execute query
    $qry_result2 = sqlsrv_query($conn, $query2, array(), array("Scrollable"=>"buffered")) or die(sqlsrv_error());
    //Build Result String
    $display_string = "<table>";
    $display_string .= "<tr>";
    $display_string .= "<th>ESL</th>";
    $display_string .= "<th>Barcode</th>";
    $display_string .= "<th>Product</th>";
    $display_string .= "</tr>";

    // Insert a new row in the table for each person returned
    while($row = sqlsrv_fetch_array($qry_result2)){
    $display_string .= "<tr>";
    $display_string .= "<td>$row[ESL]</td>";
    $display_string .= "<td>$row[Product]</td>";
    $display_string .= "<td>$row[PRODUCT_NAME]</td>";-
    $display_string .= "</tr>";

    }
    $display_string .= "</table>";
    $num_results2 = sqlsrv_num_rows($qry_result2); 
    if ($num_results2 > 0){
        $retval = $display_string;
        $passed = true;
    }
    else{
    $retval = "Deze ESL is nog niet gekoppeld";
    $passed = false;
    }
    // ...
    // set the $retval message, and the $passed variable to true or false
    // ...
    break;

    default: exit;
}

include "class.xmlresponse.php";
$xml = new xmlResponse();
$xml->start();

// set the response text
$xml->command('setcontent',
array('target' => "rsp_$target", 'content' => htmlentities($retval))
);

if($passed) {
// set the message colour to green and the checkbox to checked

$xml->command('setstyle',
  array('target' => "rsp_$target", 'property' => 'color', 'value' => 'green')
);
$xml->command('setproperty',
  array('target' => "valid_$target", 'property' => 'checked', 'value' => 'true')
);

} else {
// set the message colour to red, the checkbox to unchecked and focus back on the field

$xml->command('setstyle',
  array('target' => "rsp_$target", 'property' => 'color', 'value' => 'red')
);
$xml->command('setproperty',
  array('target' => "valid_$target", 'property' => 'checked', 'value' => 'false')
);
$xml->command('focus', array('target' => $target));

}

$xml->end();
?>

2 个答案:

答案 0 :(得分:1)

$("tr#row-clck").click(function() {});仅适用于定义函数时出现的元素。

您必须以更全球化的方式调用您的函数,例如

$(document).on('click', 'tr#row-clck', function() {  
     /* your code */ 
});

答案 1 :(得分:0)

正如j_freyre所说,正如您所提到的,在创建表之前,click事件似乎已绑定。 (因为你的AJAX-Call是异步的,这似乎是原因)。

 req.open("POST",url,true); //the true marks it as asynchronous

您可以在Ajax-Call的回调函数中定义并绑定click事件。这将在你的ajaxrequest.js中围绕这段代码

case'setcontent':var target=getNodeValue(commands[i],'target');
                    var content=getNodeValue(commands[i],'content');
                    if(target&&(content!=null))
                    {
                        document.getElementById(target).innerHTML=content;
                        //Your logic for binding the event e.g. $("tr#id").on('click',...)
                    }
                    break;