简体   繁体   English

在JavaScript中访问内部div值,没有帮助的ID

[英]Accessing a inner div value in javascript, with no ids to help

I have following structure 我有以下结构

<div onClick="javascript:Myfunction('value');">

<div title="Mytitle"> </div>

</div>

Can I access in the javascript Myfunction, the title of the inner div. 我可以在javascript Myfunction中访问内部div的标题吗? There are no ids here. 这里没有ID。

If you do not want to change the html code then you can use this. 如果您不想更改html代码,则可以使用它。

function MyFunction ( elem )
{
      var child = jQuery(elem).find("div");

      alert ( child.attr("title") );
}


<div onclick="MyFunction(this);">

<div title="Mytitle"> </div>

</div>

Otherwise try this 否则试试这个

$(document).ready ( function () {           
                $('#divMain').click(function() {
                    var titleElem = $(this).find("div");                    
                    alert ( titleElem.attr("title") );                  
                });
            });

<div id="divMain" style="width: 100px; height: 100px;">
                <div title="Mytitle">
                </div>
            </div>

If it's the only div with the title you can use this selector: 如果它是唯一具有标题的div,则可以使用此选择器:

$('div[title]')

The easiest solution would to add a class or id to the div with onClick defined (I suggest moving onlick to JS code as well) 最简单的解决方案是在定义了onClick下向div添加一个类或id(我建议也将onlick移至JS代码)

<div class="myClass">
    <div title="MyTitle"> ... </div>
</div>

And in JS: 在JS中:

$('.myClass').click(function() {
    MyFunction('value');
});

Then you can find inner div with 然后您可以找到带有

$('.myClass div')

Depends if you use any JavascriptLibraries like jQuery. 取决于您是否使用任何JavascriptLibraries(如jQuery)。 If you do, you can select your objects via CSS selectors, which would be in your case 如果这样做,您可以通过CSS选择器选择对象,具体情况取决于您

$('div[onclick] > div[title]')

You'd get your inner DIV element with it. 您将获得内部DIV元素。 If there are more elments that match this criteria, you could limit them even more by attribute values. 如果还有更多符合此条件的要素,则可以通过属性值进一步限制它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM