简体   繁体   中英

How can I access dynamically added elements in views via jquery

I want to access and modify elements that are loaded with angular views. I can't seem to do it, however the element is outputted in console just fine.

Layout

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title></title>
</head>
<body data-ng-app="myapp">
    <div class="wrap">
        <div class="header"></div>
        <div class="content">
            <div data-ng-view=""></div>
        </div>
    </div>
    <script type="text/javascript" src="/content/plugins/jquery/jquery-1.10.1.min.js"></script>
    <script type="text/javascript" src="/content/plugins/bootstrap/bootstrap.min.js"></script>
    <script type="text/javascript" src="/content/plugins/pxgradient/pxgradient-1.0.2.jquery.js"></script>
    <script type="text/javascript" src="/content/plugins/angularjs/angular.js"></script>
    <script type="text/javascript" src="/content/plugins/angularjs/angular-route.js"></script>
    <script type="text/javascript" src="/content/plugins/angularjs/angular-animate.js"></script>
    <script type="text/javascript" src="/app/app.js"></script>
    <script type="text/javascript" src="/content/js/main.js"></script>
</body>
</html>

View

<div class="home">
    <h1 class="gradient">Transformation is comming</h1>
</div>

Javascript

$(function () {
    var element = $('.gradient');

    console.log(element); // this works

    element.css('color', 'red'); // this does not
});

Your element might not be "ready" yet (not in the DOM yet).

You need to access to it in jquery document.ready function If you use Angular, after the bootstrapping process is done, use Angular angular.element(document).ready

Example code: http://pairp.com/6144/1

Ok I think I have a solution, try this:

app.run(function ($rootScope) {
    $rootScope.$on('$viewContentLoaded', function () {
        $('.gradient').css('color', 'red');
    });
});

Maybe your element has a css rule that you should override. Try this:

$('.gradient').removeAttr('style').css('color','red');

你需要编写CSS作为对象:

   element.css({'color':'red'});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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