javascript - 为什么我的 ID 容器在 Document.ready 匿名函数中没有从蓝色变为红色

标签 javascript html css

我有一个由我们的网站提供商生成的表格。它有一个我访问过的 ID。在 css 中,我将颜色设置为蓝色,并且它是隐藏的。我在 document.ready 事件中有代码单击以将窗体居中放置在窗口中。 .由于 stackoverflow,它居中完美。然后我添加到点击事件以将颜色更改为红色。当我通过单击文档中的标签激活代码时,表单仍然是蓝色的。我并不特别关心颜色,但我正在尝试学习如何操作表单中的其他元素,例如稍后添加关闭按钮。

<script type="text/javascript">
    $(document).ready(function () {
        $("a").click(function () {
            var windowWidth
            var windowHeight
            var formWidth
            var formHeight
            var placementHeight
            var placementWidth
            $("#custom-form-1451559841907633284-p").attr('style', 'display:block;');
            windowWidth = window.innerWidth;
            windowHeight = window.innerHeight;
            formWidth = $('#custom-form-1451559841907633284-p').width();
            formHeight = $('#custom-form-1451559841907633284-p').height();
            placementHeight = (windowHeight - formHeight) / 2;
            placementWidth = (windowWidth - formWidth) / 2;
            $('#custom-form-1451559841907633284-p').css("top", placementHeight);
            $('#custom-form-1451559841907633284-p').css("left", placementWidth);
            $('custom-form-1451559841907633284-p').css('background-color', 'red');
            $('#custom-form-1451559841907633284-p').css('z-Index', '30');
        }); //end of a anchor click
        window.console.log("test of nested anonymous function");
    });
</script>

CSS

#custom-form-1451559841907633284-p
{
    position: fixed; 
    display: none;
    background-color: blue;
}

最佳答案

您在这一行中使用了错误的选择器:

$('custom-form-1451559841907633284-p').css('background-color', 'red');

您忘记了 custom-form-1451559841907633284-p 前面的哈希,只需将该行替换为以下内容:

$("#custom-form-1451559841907633284-p").css("background-color", "red");

你可以在这里看到一个工作示例: https://codesandbox.io/s/distracted-lichterman-vus5g

关于javascript - 为什么我的 ID 容器在 Document.ready 匿名函数中没有从蓝色变为红色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56879563/

相关文章:

PHP DOMDocument - 获取 BODY 的 html 源代码

css - 运动路径和运动旋转在 safari 中不起作用

CSS 动画没有遍历所有关键帧

javascript - 单击文本时如何切换显示/隐藏 div

javascript - 如何在moment js中将纪元时间戳转换为带时区的日期时间?

javascript - javascript 数组中未定义的第一个元素

javascript - Facebook 页面上的 Facebook 帖子

jquery - 内容隐藏不溢出隐藏

c# - 带有复选框的 asp.net 下拉列表

javascript - 如何将当前页面样式表作为字符串获取?