开发者

jquery $(this).parent()... not working from function called externally

开发者 https://www.devze.com 2023-01-24 02:19 出处:网络
as you see in the code below. I have a jQuery function called externally. I don\'t understand why I can\'t get the class name, I get an alert with \"undefined\", I was expecting \"classifyClass\" ins

as you see in the code below. I have a jQuery function called externally.

I don't understand why I can't get the class name, I get an alert with "undefined", I was expecting "classifyClass" instead, can you help? Thank you.

<html>
<head>
    <meta charset="utf-8">
    <title>parent</title>
    <script src="./js/jquery-1.4.2.min.js"></script>
    <script>
            function classify() {
                //some jquery stuff here alredy, and it works...

                //now I want to get/set the parent class, but not working (getting an alert with written "undefined", why?
                var myclass = $(this).parent().attr('class');
                alert(myclass);
            }
    </script>
</head>
<body>

<div class="pos">
    <div class="classifyClass">
        <div style="width:50px;height:50px;background-color:red;" onclick="javascript:classify();return false;"></div>
        <div style="width:50px;height:50px;background-color:green;" onclick="javascript:classify();return false;"></div>
    </div>
</div>

<div id="feedback"></div>

</body>
</html>

P.s. I don't want to use the jquery selector I need to call the function like that as I'm pass开发者_运维技巧ing some asp.net parameters, I simplified here the example to focus on the main problem. Thank you.


In your current context this refers to the window object. You either need to pass this, like this:

onclick="return classify(this);"

With matching script:

function classify(elem) {
  //some jquery stuff here alredy, and it works...
  var myclass = $(elem).parent().attr('class');
  alert(myclass);
  return false;
}

Or (better), binding unobtrusively (using your current function, this will work), like this:

$(".classifyClass > div").click(classify);
0

精彩评论

暂无评论...
验证码 换一张
取 消