将php / mysql值传递给div,可以从javascript访问

时间:2013-01-24 13:08:49

标签: php javascript html

我正在使用php创建一个<div>来表示sql中的表行。精细。 然后我使用javascript函数来测试div的值(位置,宽度等).Fine。 但我需要将另一个值传递给div以供函数检查。它存在于数据库中,但我不知道是否有(简单)方法。理想情况下,它看起来像这样。

<div id='plumber5' class='plumber' style='width:50px;left:100px' value='numericValue'>Derek</div>

内联样式是在php中生成的,除了按js可以检测的样式(宽度,高度等)之外,不能想到传递数值的方法。

例如

<script>
a=document.getElementById('plumber5');
if (a.style.width=>75){
execute something here}
</script>

而不是使用样式作为测试源

非常麻烦! 感谢

编辑 - 解决方案

function checkData($type){  
    a = document.getElementsByClassName($type);
    for(i = 0; i < a.length; i++)
    {
    if (a[i].getAttribute('data-dob') >= sessionStorage.Value) {
    // execute something here
    }
    }

}

4 个答案:

答案 0 :(得分:2)

您可以使用HTML5的数据属性向HTML标记添加一些自定义数据:

http://ejohn.org/blog/html-5-data-attributes/

示例:

<div data-value='10' id='plumber5' class='plumber' style='width: 50px; left: 100px;'>
    Derek
</div>

你可以得到这样的价值:

<script>
    a = document.getElementById('plumber5');
    if (a.getAttribute('data-value') => 75) {
        // execute something here
    }
</script>

答案 1 :(得分:1)

您可以这样使用data-属性:

<div id='plumber5' class='plumber' style='width: 50px; left: 100px'
     data-value='numericValue'>Derek</div>

注意: HTML5数据属性仅在IE 9 +,Chrome 12 +,Firefox 5 +等现代浏览器中受支持。

请注意,style属性中存在错误。替换:

style='width=50px;left=100px'

使用:

style='width: 50px; left: 100px'

答案 2 :(得分:1)

HTML5支持data-*代码属性,因此您可以使用:

<div id='plumber5' class='plumber' data-value='numericValue' data-myothervalue='otherOne'>
    Derek
</div>

修改

由于评论中看起来很乱,以下是访问示例值的方法:

var myDiv = document.getElementById('plumber5'); 
var myVal = myDiv.getAttribute('data-value');         // 'numericValue'
var myVal2 = myDiv.getAttribute('data-myothervalue'); // 'otherOne'

答案 3 :(得分:1)

如果您的受众群体不支持HTML5,您可以嵌入以下内容:

<div id="plumber5" class="plumber" style="width:50px;left:100px">
    Derek
    <div style="display: none">numericValue</div>
</div>

这会隐藏视图中的值,但允许您访问它查看Javascript。