日期:2014-05-16  浏览次数:20392 次

jquery 根据DIV内容 怎么得到DIV的ID
比如
  <div id="code1">中国</div>
  <div id="adeg">美国</div>
  <div id="dg3g">英国</div>
  <div id="gjr4">德国</div>
  <div id="bkjt">法国</div>
我要怎么根据“德国”得到其相应的id=gjr4 ?

------解决方案--------------------
try : $("div:contains('德国')").eq(0).attr("id");

但是contains不是精确匹配 。
------解决方案--------------------
笨方法遍历吧
 
JScript code

   $("div").each(function() { 
    if($(this).html()=="德国"){alert($(this).attr("id"))}
    });

------解决方案--------------------
JScript code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="ec/jquery/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function test(only) {
            var $objs = $("div[id]:contains('德国')");
            var arr = [];
            $objs.each(function () {
                if (only && $(this).text().length > 2)
                    return false;
                arr.push($(this).attr("id"));
            });
            alert(arr);
        }
    </script>
</head>
<body>
    <div id="code1">中国</div>
    <div id="adeg">美国</div>
    <div id="dg3g">英国</div>
    <div id="gjr4">德国</div>
    <div id="bkjt">法国</div>
    <div id="Div1">德国1</div>
    <div id="Div2">德国2</div>
    <div id="Div3">德国3</div>
    <div id="Div4">德国4</div>
    <input type="button" value="取得包含德国的 div 的id" onclick="test(false)" />
    <input type="button" value="取得只包含德国的 div 的id" onclick="test(true)" />
</body>
</html>