动态添加按钮d3.js

时间:2019-11-27 21:20:59

标签: javascript d3.js

这似乎是一个微不足道的问题,但是我一生无法找到令人满意的答案。

如何在不将其硬编码到页面中或不对“ onclick”属性进行字符串化的情况下添加具有绑定功能的按钮?

@mock_batch
@mock_iam
def test_create_compute_environment(lims_objs):
    client = boto3.client("batch")
    iam = boto3.resource("iam")
    service_role = iam.create_role(
        RoleName="BatchServiceRole", AssumeRolePolicyDocument="AWSBatchServiceRole"
    )
    instance_profile = iam.create_instance_profile(
        InstanceProfileName="InstanceProfile"
    )
    instance_profile.add_role(RoleName=service_role.name)
    for elem in iam.instance_profiles.all():
        print(elem, elem.arn)

    for elem in iam.roles.all():
        print(elem)

    response = client.create_compute_environment(
        computeEnvironmentName="compute_environment",
        type="MANAGED",
        state="ENABLED",
        computeResources={
            "type": "EC2",
            "minvCpus": 0,
            "maxvCpus": 256,
            "desiredvCpus": 2,
            "instanceTypes": ["optimal"],
            "imageId": "test",
            "subnets": [],
            "securityGroupIds": [],
            "ec2KeyPair": "",
            "instanceRole": instance_profile.arn,
            "tags": {},
        },
        serviceRole=service_role.arn,
    )

相反,我看到人们这样做的唯一方法是

iam.InstanceProfile(name='InstanceProfile') arn:aws:iam::123456789012:instance-profile/InstanceProfile
iam.Role(name='BatchServiceRole')

似乎很笨拙。我需要为按钮提供某种数据还是什么?

2 个答案:

答案 0 :(得分:2)

我是D3程序员,我必须说,在那些年里,我从未见过使用您声称是唯一看到的设置onclick属性的方法的单个D3代码:< / p>

selection.attr("onclick", "foo()")

它确实有效,但这不是惯用的D3。在D3中,我们使用on方法。但是,第一个代码段的问题在于它会立即调用该函数:

d3.select("body")
  .append("button")
  .html("Click me")
  .on("click", console.log("you clicked me"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

您可以看到控制台显示“您单击了我” ,没有任何点击。因此,为了使其正常工作,我们不应该调用该函数。有趣的是,console.log接受3个参数,看看如果我们不调用console.log会发生什么:

d3.select("body")
  .append("button")
  .html("Click me")
  .on("click", console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

现在console.log可以在单击按钮时使用,因为您将其作为函数引用传递了。但是,第一个值为undefined,因为您没有将任何字符串传递给console.log

话虽如此,你想要的是:

d3.select("body")
  .append("button")
  .html("Click me")
  .on("click", () => {
    console.log("you clicked me")
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

现在,您正在向click事件传递适当的函数,该事件将在您单击时调用。

答案 1 :(得分:0)

当您:

some_div_selection.append("button").text("+").on("click", function(){console.log("You clicked me")});
相关问题